﻿Imports Microsoft.VisualBasic

Namespace MyDBase



    Partial Public Class GloukDB


        Partial Class helper

            Partial Class rel(Of Tresult As {New, Class})

                Partial Class helper

                    Partial Class _Query_Account

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "account_code", q.TabName & ".account_code").
                                Select("account.*")

                        End Function

                    End Class

                    Partial Class Account

                        Public Function Account_Link() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_link", "account_link_id", "account.id").
                                Select("account_link.*")

                        End Function
                        Public Function Account_Add_Info() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_add_info", "account_id", "account.id").
                                Select("account_add_info.*")


                        End Function
                        Public Function Account_Option() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_option", "account_id", "account.id").
                                Select("account_option.*")


                        End Function

                        Public Function Account_Update() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_update", "account_id", "account.id").
                                Select("account_update.*")


                        End Function
                        Public Function User_Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("user_account", "account_id", "account.id").
                                Select("user_account.*")

                        End Function
                        Public Function Account_Auth() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_auth", "account_id", "account.id").
                                Select("account_auth.*")

                        End Function
                        'Public Function User_Account_Enabled() As BuildQuery(Of Tresult)

                        '    Return q.BY.User_Account.Enabled.
                        '        Join("user_account", "account_id", "account.id").
                        '        Select("user_account.*")

                        'End Function

                        Public Function Message_Post() As BuildQuery(Of Tresult)

                            Return q.
                                Join("message_post", "account_id", "account.id").
                                Select("message_post.*")

                        End Function
                        Public Function Private_Post() As BuildQuery(Of Tresult)

                            Return q.
                                Join("private_post", "account_id", "account.id").
                                Select("private_post.*")

                        End Function
                        Public Function Private_Post_To_Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("private_post", "to_account_id", "account.id").
                                Select("private_post.*")

                        End Function
                        Public Function Private_Post_Last_To_Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("private_post_last", "to_account_id", "account.id").
                                Select("private_post_last.*")

                        End Function



                        Public Function Share_Detail() As BuildQuery(Of Tresult)

                            Return q.
                                Join("share_detail", "account_id", "account.id").
                                Select("share_detail.*")

                        End Function
                        Public Function Share_Post() As BuildQuery(Of Tresult)

                            Return q.
                                Join("share_post", "account_id", "account.id").
                                Select("share_post.*")

                        End Function
                        Public Function Categorize_Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("categorize_account", "account_categozie_id", "account.id").
                                Select("categorize_account.*")

                        End Function
                        'Public Function AccountPost() As BuildQuery(Of Tresult)

                        '    Return q.
                        '        Join("account_post", "account_id", "account.id").
                        '        Select("account_post.*")

                        'End Function

                        Public Function Auto_Follow_Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Auto_Follow_Account", "account_id", "account.id").
                                Select("Auto_Follow_Account.*")

                        End Function
                        Public Function Auto_Follow_Profile() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Auto_Follow_Profile", "account_id", "account.id").
                                Select("Auto_Follow_Profile.*")

                        End Function


                        Public Function Auto_Follow_Account_to_foll() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Auto_Follow_Account", "account_to_foll_id", "account.id").
                                Select("Auto_Follow_Account.*")

                        End Function

                        Public Function Auto_Follow_Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Auto_Follow_Query", "account_id", "account.id").
                                Select("Auto_Follow_Query.*")

                        End Function
                        Public Function Task_Send() As BuildQuery(Of Tresult)

                            Return q.
                                Join("task_send", "share_account_id", "account.id").
                                Select("task_send.*")


                        End Function
                        Public Function Listen_Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("listen_query", "account_id", "account.id").
                                Select("listen_query.*")


                        End Function

                    End Class
                    Partial Class _Account_Link

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", q.TabName & ".account_link_id").
                                Select("account.*")

                        End Function

                        Public Function Account_Update() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_update", "account_id", q.TabName & ".account_link_id").
                                Select("account_update.*")

                        End Function
                        Public Function Account_Add_Info() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_add_info", "account_id", q.TabName & ".account_link_id").
                                Select("account_add_info.*")

                        End Function


                    End Class

                    Partial Class Account_Add_Info

                        Public Function Place() As BuildQuery(Of Tresult)

                            Return q.
                                Join("place", "id", "account_add_info.place_id").
                                Select("place.*")

                        End Function

                        Public Function Language() As BuildQuery(Of Tresult)

                            Return q.
                                Join("language", "lang_code", "account_add_info.lang").
                                Select("language.*")

                        End Function


                    End Class
                    Partial Class Alert

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "alert.account_id").
                                Select("account.*")

                        End Function

                        Public Function FromAccount() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "alert.from_account_id", "from_account", "").
                                Select("from_account.*")

                        End Function

                        Public Function User_Alert() As BuildQuery(Of Tresult)

                            Return q.
                                Join("User_Alert", "alert_id", "alert.id").
                                Select("User_Alert.*")

                        End Function


                    End Class
                    Partial Class Private_Post

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "private_post.account_id").
                                Select("account.*")

                        End Function

                        Public Function ToAccount() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "private_post.to_account_id", "to_account", "").
                                Select("to_account.*")

                        End Function


                    End Class
                    Partial Class Private_Post_Last

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "Private_Post_Last.account_id").
                                Select("account.*")

                        End Function

                        Public Function ToAccount() As BuildQuery(Of Tresult)

                            Return q.
                                Join("Account", "id", "Private_Post_Last.to_account_id", "to_account", "").
                                Select("to_account.*")

                        End Function


                    End Class
                    Partial Class Categorize

                        Public Function Categorize_Follower() As BuildQuery(Of Tresult)

                            Return q.
                                Join("categorize_follower", "categorize_id", "categorize.id").
                                Select("categorize_follower.*")

                        End Function

                        Public Function Folder() As BuildQuery(Of Tresult)

                            Return q.
                                Join("folder", "ref_id", "categorize.folder_id").
                                Select("folder.*")

                        End Function

                    End Class
                    Partial Class Categorize_Account

                        Public Function Categorize() As BuildQuery(Of Tresult)

                            Return q.
                                Join("categorize", "id", "Categorize_Account.categorize_id").
                                Select("categorize.*")

                        End Function

                    End Class

                    Partial Class Categorize_Follower

                        Public Function Categorize() As BuildQuery(Of Tresult)

                            Return q.
                                Join("categorize", "id", "categorize_follower.categorize_id").
                                Select("categorize.*")

                        End Function

                    End Class



                    Partial Class Listen_Query
                        Public Function Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("query", "id", "listen_query.query_id").
                                Select("query.*")

                        End Function
                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "listen_query.account_id").
                                Select("Account.*")

                        End Function


                    End Class
                    'Partial Class AccountPost

                    '    'Public Function QueryPost() As BuildQuery(Of Tresult)

                    '    '    Return q.
                    '    '        Join("query_post", "post_id", "post.id").
                    '    '        Select("query_post.*")

                    '    'End Function
                    '    Public Function Account() As BuildQuery(Of Tresult)

                    '        Return q.
                    '            Join("account", "id", "account_post.account_id").
                    '            Select("account.*")

                    '    End Function

                    '    Public Function AccountLink() As BuildQuery(Of Tresult)

                    '        Return q.
                    '            Join("account_link", "account_link_id", "account_post.account_id").
                    '            Select("account_link.*")

                    '    End Function

                    'End Class

                    Partial Class Auto_Follow_Query
                        Public Function Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("query", "id", "Auto_Follow_Query.query_id").
                                Select("query.*")

                        End Function

                    End Class
                    Partial Class Auto_Follow_Account
                        Public Function Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("query", "id", "Auto_Follow_Account.source_id").
                                Select("query.*")

                        End Function

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "Auto_Follow_Account.account_to_foll_id").
                                Select("account.*")

                        End Function



                    End Class
                    Partial Class Auto_Follow_Profile
                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "Auto_Follow_Profile.profile_account_id").
                                Select("account.*")

                        End Function

                    End Class
                    Partial Class Query
                        Public Function Folder() As BuildQuery(Of Tresult)

                            Return q.
                                Join("folder", "ref_id", "query.folder_id").
                                Select("folder.*")

                        End Function
                        'Public Function Query_Post() As BuildQuery(Of Tresult)

                        '    Return q.
                        '        Join("query_post", "query_id", "query.id").
                        '        Select("query_post.*")

                        'End Function
                        Public Function Categorize() As BuildQuery(Of Tresult)

                            Return q.
                                Join("categorize", "query_id", "query.id").
                                Select("categorize.*")

                        End Function
                        'Public Function Query_Account() As BuildQuery(Of Tresult)

                        '    Return q.
                        '        Join("query_account", "query_id", "query.id").
                        '        Select("query_account.*")

                        'End Function

                        Public Function Listen_Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("listen_query", "query_id", "query.id").
                                Select("listen_query.*")

                        End Function

                        Public Function Auto_Follow_Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("auto_follow_query", "query_id", "query.id").
                                Select("auto_follow_query.*")

                        End Function

                    End Class
                    'Partial Class Query_Account
                    '    Public Function Account() As BuildQuery(Of Tresult)

                    '        Return q.
                    '            Join("account", "account_code", "query_account.account_code").
                    '            Select("account.*")

                    '    End Function
                    'End Class

                    Partial Class Folder
                        Public Function Query() As BuildQuery(Of Tresult)

                            Return q.
                                Join("query", "folder_id", "folder.ref_id").
                                Select("query.*")

                        End Function
                    End Class

                    Partial Class Message_Post
                        Public Function Account_To() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "message_post.to_account_id").
                                Select("account.*")

                        End Function
                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "message_post.account_id").
                                Select("account.*")

                        End Function

                    End Class
                    Partial Class Profile
                        Public Function Folder() As BuildQuery(Of Tresult)

                            Return q.
                                Join("folder", "ref_id", "profile.folder_id").
                                Select("folder.*")

                        End Function
                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "profile.account_id").
                                Select("account.*")

                        End Function

                        Public Function auto_follow_profile() As BuildQuery(Of Tresult)

                            Return q.
                                Join("auto_follow_profile", "account_id", "profile.account_id").
                                Select("auto_follow_profile.*")

                        End Function

                    End Class
                    Partial Class Share_Detail

                        Public Function Share_Post() As BuildQuery(Of Tresult)

                            Return q.
                                Join("share_post", "id", "share_detail.share_post_id").
                                Select("share_post.*")

                        End Function

                    End Class
                    Partial Class Share_Post

                        Public Function Account() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "share_post.account_id").
                                Select("account.*")

                        End Function

                        Public Function Share_Detail() As BuildQuery(Of Tresult)

                            Return q.
                                Join("share_detail", "share_post_id", "share_post.id").
                                Select("share_detail.*")

                        End Function


                    End Class


                    Partial Class Task_Send

                        Public Function FeedRss() As BuildQuery(Of Tresult)

                            Return q.
                                Join("feedrss", "id", "task_send.feedrss_id").
                                Select("feedrss.*")

                        End Function

                        Public Function Account_Share() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account", "id", "task_send.share_account_id").
                                Select("account.*")

                        End Function

                        Public Function Account_Update_Share() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_update", "account_id", "task_send.share_account_id").
                                Select("account_update.*")

                        End Function
                        Public Function Account_Add_Info_Share() As BuildQuery(Of Tresult)

                            Return q.
                                Join("account_add_info", "account_id", "task_send.share_account_id").
                                Select("account_add_info.*")

                        End Function
                        Public Function Task_Scheduler() As BuildQuery(Of Tresult)

                            Return q.
                                Join("task_scheduler", "task_send_id", "task_send.id").
                                Select("task_scheduler.*")

                        End Function

                    End Class
                    Partial Class User_Plan

                        Public Function Plan() As BuildQuery(Of Tresult)

                            Return q.
                                Join("plan", "id", "User_Plan.plan_id").
                                Select("plan.*")

                        End Function
                    End Class
                    Partial Class User_Promo

                        Public Function Promo() As BuildQuery(Of Tresult)

                            Return q.
                                Join("promo", "id", "User_promo.promo_id").
                                Select("promo.*")

                        End Function
                    End Class

                    Partial Class User_Account

                        Public Function User() As BuildQuery(Of Tresult)

                            Return q.
                                Join("user", "id", "user_account.user_id").
                                Select("user.*")

                        End Function


                    End Class
                End Class

            End Class
            Partial Class by(Of Tresult As {New, Class})

                Partial Class helper

                    Partial Class Account



                    End Class
                    Partial Class _Account_Post

                        Public Function _Post_Code(v As String) As BuildQuery(Of Tresult)
                            Return q.Where("Post_Code", "=", v)
                        End Function

                        Public Function _Account_Id(v As Integer) As BuildQuery(Of Tresult)
                            Return q.Where("Account_Id", "=", v)
                        End Function


                    End Class

                    Partial Class _Query_Post

                        Public Function _Post_Code(v As String) As BuildQuery(Of Tresult)
                            Return q.Where("Post_Code", "=", v)
                        End Function

                        Public Function _Query_id(v As Integer) As BuildQuery(Of Tresult)
                            Return q.Where("query_id", "=", v)
                        End Function


                    End Class
                    Partial Class _Query_Account

                        Public Function _Query_id(v As Integer) As BuildQuery(Of Tresult)
                            Return q.Where("query_id", "=", v)
                        End Function


                    End Class

                    Partial Class _Trend


                        Public Function _Account_Id(v As Integer) As BuildQuery(Of Tresult)
                            Return q.Where("Account_Id", "=", v)
                        End Function

                        'Public Function _Account_Id(Id As Integer, TrendType As mDB._Trend.Type) As BuildQuery(Of Tresult)

                        '    Return q.BY._Trend.Account_Id(Id).
                        '    Where("trend_type_id", "=", TrendType)

                        'End Function
                        'Public Function _Account_Id(Id As Integer, TrendType As mDB._Trend.Type, d As Date) As BuildQuery(Of Tresult)

                        '    Return q.BY._Trend._Account_Id(Id, TrendType).
                        '        Where("trend_date", "=", d)

                        'End Function

                    End Class

                    Partial Class _Account_Link

                        Public Function _Account_Id(v As Integer) As BuildQuery(Of Tresult)
                            Return q.Where(q.TabName & ".Account_Id", "=", v)
                        End Function

                        'Public Function _Account_ID(ID As Integer, LinkType As mDB._Account_Link.Type) As BuildQuery(Of Tresult)

                        '    Return q.BY._Account_Link._Account_Id(ID).
                        '        Where("link_type_id", "=", LinkType)

                        'End Function
                        'Public Function _Account_ID(ID As Integer, LinkTypes As List(Of mDB._Account_Link.Type)) As BuildQuery(Of Tresult)

                        '    Return q.BY._Account_Link._Account_Id(ID).
                        '        Where("link_type_id", "IN", LinkTypes)

                        'End Function

                        'Public Function _Account_ID(ID As Integer, LinkType As mDB._Account_Link.Type, AccountLinkID As Integer) As BuildQuery(Of Tresult)

                        '    Return q.BY._Account_Link._Account_Id(ID, LinkType).
                        '        Where("account_link_id", "=", AccountLinkID)

                        'End Function

                        'Public Function Account_ID_Analysis(ID As Integer, analysis As Boolean) As BuildQuery(Of Tresult)

                        '    Return q.BY._Account_Link.Account_Id(ID).
                        '        Where("analysis", "=", analysis)

                        'End Function
                    End Class

                    Partial Class List




                    End Class

                    Partial Class List_Account

                        Public Function List_Id(Id As Integer, Account_ID As Integer) As BuildQuery(Of Tresult)

                            Return q.BY.List_Account.List_Id(Id).
                                Where("Account_ID", "=", Account_ID)

                        End Function

                    End Class

                    Partial Class Listen_Query

                        Public Function Query_Id(Id As Integer) As BuildQuery(Of Tresult)

                            Return q.
                                Where("listen_query.query_id", "=", Id)

                        End Function
                        Public Function Account_Id(AccountId As Integer, QueryId As Integer) As BuildQuery(Of Tresult)

                            Return q.BY.Listen_Query.Account_Id(AccountId).
                                Where("listen_query.query_id", "=", QueryId)

                        End Function


                    End Class

                    Partial Class Group_Account

                        Public Function User_Id(Id As Integer, TypeId As Integer) As BuildQuery(Of Tresult)

                            Return q.BY.Group_Account.User_Id(Id).
                                Where("Group_Account.group_type_id", "=", TypeId)

                        End Function

                    End Class

                    Partial Class Folder

                        Public Function User_Id(Id As Integer, TypeId As mDB.Folder.Type) As BuildQuery(Of Tresult)

                            Return q.BY.Folder.User_Id(Id).
                                Where("folder.folder_type_id", "=", TypeId)

                        End Function
                        Public Function User_Id(Id As Integer, TypeId As mDB.Folder.Type, FolderParentId As Integer) As BuildQuery(Of Tresult)

                            Return q.BY.Folder.User_Id(Id, TypeId).
                                Where("folder.folder_parent_id", "=", FolderParentId)

                        End Function

                    End Class


                    Partial Class Categorize

                        'Public Function Account_Id(Id As Integer, ListTypeId As mDB.Categorize.Type) As BuildQuery(Of Tresult)
                        '    Return q.BY.Categorize.Account_Id(Id).
                        '        Where("categorize.categorize_type_id", "=", ListTypeId)
                        'End Function

                        'Public Function Account_Id(Id As Integer, folder_id As Integer) As BuildQuery(Of Tresult)
                        '    Return q.BY.Categorize.Account_Id(Id).
                        '        Where("categorize.folder_id", "=", folder_id)
                        'End Function

                    End Class

                    Partial Class Categorize_Follower
                        Public Function Account_Id(AccountId As Integer, categorizeid As Integer) As BuildQuery(Of Tresult)
                            Return q.BY.Categorize_Follower.Account_Id(AccountId).
                                Where("Categorize_Follower.categorize_id", "=", categorizeid)
                        End Function

                    End Class

                    Partial Class Categorize_Account
                        Public Function Account_Id(AccountId As Integer, categorizeid As Integer) As BuildQuery(Of Tresult)
                            Return q.BY.Categorize_Account.Account_Id(AccountId).
                                Where("Categorize_Account.categorize_id", "=", categorizeid)
                        End Function

                        Public Function Account_Id(AccountId As Integer, categorizeids As List(Of Integer)) As BuildQuery(Of Tresult)
                            Return q.BY.Categorize_Account.Account_Id(AccountId).
                                Where("Categorize_Account.categorize_id", "IN", categorizeids)
                        End Function

                    End Class

                    Partial Class Query

                        'Public Function UserId(Id As Integer, QueryTypeId As Integer) As BuildQuery(Of Tresult)

                        '    Return q.BY.Query.UserId(Id).
                        '        Where("query.query_type_id", "=", QueryTypeId)

                        'End Function
                        'Public Function UserId(Id As Integer, QueryTypeId As Integer, FolderParentId As Integer) As BuildQuery(Of Tresult)

                        '    Return q.BY.Query.UserId(Id, QueryTypeId).
                        '        Where("query.folder_id", "=", FolderParentId)

                        'End Function

                    End Class
                    'Partial Class Query_Post

                    '    Public Function Query_Id(Id As Integer, PostCode As String) As BuildQuery(Of Tresult)

                    '        Return q.BY.Query_Post.Query_Id(Id).
                    '            Where("query_post.post_code", "=", PostCode)

                    '    End Function

                    'End Class
                    'Partial Class Trend

                    '    Public Function Account_Id(Id As Integer, TrendType As mDB.Trend.Type) As BuildQuery(Of Tresult)

                    '        Return q.BY.Trend.Account_Id(Id).
                    '        Where("trend.trend_type_id", "=", TrendType)

                    '    End Function
                    '    Public Function Account_Id(Id As Integer, TrendType As mDB.Trend.Type, d As Date) As BuildQuery(Of Tresult)

                    '        Return q.BY.Trend.Account_Id(Id, TrendType).
                    '            Where("trend.trend_date", "=", d)

                    '    End Function

                    'End Class

                    Partial Class Favorite_Post
                        Public Function Account_Id(AccountId As Integer, PostCode As String) As BuildQuery(Of Tresult)
                            Return q.BY.Favorite_Post.Account_Id(AccountId).
                                Where("favorite_post.post_code", "=", PostCode)
                        End Function

                    End Class
                    Partial Class Follower_Analysis

                        Public Function Account_Id(Id As Integer, AnalysisType As mDB.Follower_Analysis.Type) As BuildQuery(Of Tresult)

                            Return q.BY.Follower_Analysis.Account_Id(Id).
                            Where("analysis_type_id", "=", AnalysisType)

                        End Function
                        Public Function Account_Id(Id As Integer, AnalysisType As mDB.Follower_Analysis.Type, DataType As Integer) As BuildQuery(Of Tresult)

                            Return q.BY.Follower_Analysis.Account_Id(Id, AnalysisType).
                                Where("data_type_id", "=", DataType)

                        End Function


                    End Class

                    Partial Class Auto_Follow_Query
                        Public Function Account_Id(Id As Integer, QueryId As Integer) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("query_id", "=", QueryId)

                        End Function

                    End Class
                    Partial Class Auto_Follow_Profile
                        Public Function Account_Id(Id As Integer, ProfileAccountId As Integer) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("profile_account_id", "=", ProfileAccountId)

                        End Function

                    End Class
                    Partial Class Auto_Follow_Account

                        Public Function Account_Id(Id As Integer, AccFollID As Integer) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("account_to_foll_id", "=", AccFollID)

                        End Function
                        Public Function Account_Id(Id As Integer, StatusType As mDB.Auto_Follow_Account.StatusType) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("status_id", "=", StatusType)

                        End Function
                        'Public Function AccountId(Id As Integer) As BuildQuery(Of Tresult)

                        '    '    Return q.Where("account_id", "=", Id)

                        'End Function
                    End Class

                    Partial Class Private_Post

                        Public Function Account_Id(Id As Integer, toAccountID As Integer) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("to_account_id", "=", toAccountID)

                        End Function
                        Public Function Account_Id(Id As Integer, send As Boolean) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("is_sent", "=", send)

                        End Function

                    End Class

                    Partial Class Private_Post_Last
                        Public Function Account_Id(Id As Integer, toAccountID As Integer, IsSend As Boolean) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("to_account_id", "=", toAccountID, "is_sent", "=", IsSend)

                        End Function

                        Public Function Account_Id(Id As Integer, IsSend As Boolean) As BuildQuery(Of Tresult)

                            Return Me.Account_Id(Id).
                                Where("is_sent", "=", IsSend)

                        End Function

                    End Class

                    Partial Class User_Account

                        Public Function User_Id(UserId As Integer, AccountId As Integer) As BuildQuery(Of Tresult)

                            Return Me.User_Id(UserId).BY.User_Account.Account_Id(AccountId)


                        End Function

                        Public Function Account_Id(Id As Integer) As BuildQuery(Of Tresult)

                            Return q.Where("user_account.account_id", "=", Id)

                        End Function

                    End Class

                    Partial Class Plan


                        Public Function Plan_Type_Id(Id As Integer) As BuildQuery(Of Tresult)

                            Return q.Where("plan.plan_type_id", "=", Id)

                        End Function

                    End Class



                    Partial Class Account_Auth

                        'Public Function Account_Id(Id As Integer) As BuildQuery(Of Tresult)

                        '    Return q.Where("user_account.account_id", "=", Id)

                        'End Function


                        Public Function Enabled() As BuildQuery(Of Tresult)

                            Return q.Where("disabled", "=", 0)

                        End Function
                        Public Function AnalysisFollower() As BuildQuery(Of Tresult)

                            Return q.Where("analysis_followers", "=", True)

                        End Function


                        Public Function Network_id(n As MyApp.Network.AccType) As BuildQuery(Of Tresult)

                            Return q.Where("account_auth.network_id", "=", n)

                        End Function

                    End Class


                    Partial Class ShareDetail

                    End Class

                End Class

            End Class

            Partial Class view

                Public Function Account_UserEnabled() As BuildQuery(Of mDB.Account)

                    Return db.TAB.Account.
                        REL.Account.Account_Auth.
                        REL.Account.User_Account.
                        BY.Account_Auth.Enabled.
                        GroupBy("account.id")

                End Function
                Public Function Account_UserAnalysisFollowers() As BuildQuery(Of mDB.Account)

                    Return Account_UserEnabled.BY.Account_Auth.AnalysisFollower

                End Function


                'Public Function Account_ContactsFilter(
                '    AccountID As Integer, FromDate As Date, ToDate As Date,
                '    idsLink As List(Of Integer), idscat As List(Of Integer), idsLang As List(Of String), idsgend As List(Of Integer), idsBusin As List(Of Integer)
                ') As BuildQuery(Of mDB.Account)

                '    Dim q = db.TAB.Account.
                '        REL.Account.Account_Link.
                '        REL.Account.Account_Add_Info.
                '        REL.Account.Account_Update

                '    If idsLink.Count <> 0 Then
                '        Dim links = idsLink.Select(Function(o) DirectCast(o, mDB.Account_Link.Type)).ToList
                '        q.BY.Account_Link.Account_Id(AccountID, links)
                '    Else
                '        q.BY.Account_Link.Account_Id(AccountID)
                '    End If

                '    If idscat.Count <> 0 Then
                '        q.REL.Account.Categorize_Account()
                '        q.BY.Categorize_Account.Account_Id(AccountID, idscat)
                '    End If

                '    If idsLang.Count <> 0 Then
                '        q.Where("lang", "IN", idsLang)
                '    End If

                '    If idsgend.Count <> 0 Then
                '        q.Where("gender_type_id", "IN", idsgend)
                '    End If

                '    If idsBusin.Count <> 0 Then
                '        q.Where("business_type_id", "IN", idsBusin)
                '    End If

                '    If FromDate > Date.MinValue Then
                '        q.Where("create_date", ">=", FromDate)
                '    End If

                '    If ToDate > Date.MinValue Then
                '        q.Where("create_date", "<", ToDate.AddDays(1))
                '    End If

                '    Return q

                'End Function

                'Public Function Account_UserAccountForUpdate(d As Date) As BuildQuery(Of mDB.Account)
                '    Return db.TAB.Account.
                '        REL.Account.User_Account.
                '        Where("profile_update", "<", d)

                'End Function

                'Public Function Account_TaskSend_SharePost(AccountID As Integer) As BuildQuery(Of mDB.Account)

                '    Return db.TAB.Account.
                '        REL.Account.Account_Update.
                '        REL.Account.Task_Send.
                '        BY.Task_Send.Account_Id(AccountID).
                '        Where(
                '            "enabled_task", "=", True,
                '            "share_account_id", "<>", 0
                '        )

                'End Function



            End Class
        End Class


        'Partial Public Class BuildQuery(Of Tresult As {New, Class})



        'End Class





#Region "Oggetti DB"

        Partial Class Alert
            Public Enum Type
                MESSAGE = 1
                PRIVATE_POST = 2
                'TO_POST_SHARE = 3
            End Enum

            Public Shared Function AlertMessage(AlertType As mDB.Alert.Type) As String
                Select Case AlertType
                    Case mDB.Alert.Type.MESSAGE
                        Return "mentioned you"
                    Case mDB.Alert.Type.PRIVATE_POST
                        Return "sent you a message"
                    Case Else
                        Return ""
                End Select
            End Function


        End Class
        Public Interface IAccountAnalysis

            Function GetFollowerAnalysis(AnalysisType As Follower_Analysis.Type) As List(Of Follower_Analysis)
            Function GetFollowerAnalysisValue(AnalysisType As Follower_Analysis.Type, DataType As Integer) As Integer

            Function GetTrendSum(t As _Trend.Type, fromDate As Date, ToDate As Date) As Integer
            Function GetTrendValue(t As _Trend.Type, D As Date) As Integer
            Function GetTrend(t As _Trend.Type, FromDate As Date, ToDate As Date, groupby As DateInterval) As List(Of _Trend)

        End Interface
        Public Interface IQueryAnalysis

            Function GetTrendAccount(FromDate As Date, ToDate As Date) As List(Of mDB._Query_Account)

        End Interface

        Partial Public Class Account


            Public Overrides Function ToString() As String

                Return SF("'{0}' [{1}]", Me.Fullname, Me.Id)

            End Function

            Public Enum BusinessType
                UNKNOW = -1
                NOT_ASSIGNED = 0
                [PRIVATE] = 1
                [BUSINESS] = 2

                'TO_POST_SHARE = 3
            End Enum

            Public Enum StatusType
                NOT_ASSIGNED = 0
                FAKE = 1
                INACTIVE = 2
                LOW_ACTIVITY = 3
                MEDIUM_ACTIVITY = 4
                HIGHT_ACTIVITY = 5

                'TO_POST_SHARE = 3
            End Enum

            Public Enum UpdatePostMode
                FOLLOWER
                PROFILE
            End Enum
            Public Enum UpdateAccountMode
                ALL
                ENGAGEMENT
                AUTO_FOLLOW
                FRIENDS
            End Enum


#Region "TABELLE"


            Public ReadOnly Property Tab_Account_Filter() As BuildQuery(Of Account_Filter)
                Get
                    Return DB.TAB.Account_Filter.BY.Account_Filter.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_List() As BuildQuery(Of List)
                Get
                    Return DB.TAB.List.BY.List.Account_Id(Me.Id)
                End Get
            End Property


            Public ReadOnly Property Tab_Categorize_Follower() As BuildQuery(Of Categorize_Follower)
                Get
                    Return DB.TAB.Categorize_Follower.BY.Categorize_Follower.Account_Id(Me.Id)
                End Get
            End Property
            Public Function View_Categorize() As BuildQuery(Of Categorize)
                Return DB.TAB.Categorize.REL.Categorize.Categorize_Follower.BY.Categorize_Follower.Account_Id(Me.Id)
            End Function

            Public ReadOnly Property Tab_Categorize_Follower(CategorizeId As Integer) As BuildQuery(Of Categorize_Follower)
                Get
                    Return DB.TAB.Categorize_Follower.BY.Categorize_Follower.Account_Id(Me.Id, CategorizeId)
                End Get
            End Property
            Public ReadOnly Property Tab_Categorize_Account() As BuildQuery(Of Categorize_Account)
                Get
                    Return DB.TAB.Categorize_Account.BY.Categorize_Account.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Categorize_Account(CategorizeId As Integer) As BuildQuery(Of Categorize_Account)
                Get
                    Return DB.TAB.Categorize_Account.BY.Categorize_Account.Account_Id(Me.Id, CategorizeId)
                End Get
            End Property

            Public ReadOnly Property Tab_Follower_Analysis() As BuildQuery(Of Follower_Analysis)
                Get
                    Return DB.TAB.Follower_Analysis.BY.Follower_Analysis.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Follower_Analysis(AnalysisType As Follower_Analysis.Type) As BuildQuery(Of Follower_Analysis)
                Get
                    Return DB.TAB.Follower_Analysis.BY.Follower_Analysis.Account_Id(Me.Id, AnalysisType)
                End Get
            End Property
            Public ReadOnly Property Tab_Follower_Analysis(AnalysisType As Follower_Analysis.Type, DataType As Integer) As BuildQuery(Of Follower_Analysis)
                Get
                    Return DB.TAB.Follower_Analysis.BY.Follower_Analysis.Account_Id(Me.Id, AnalysisType, DataType)
                End Get
            End Property

            Public ReadOnly Property Tab_Auto_Follow_Query() As BuildQuery(Of Auto_Follow_Query)
                Get
                    Return DB.TAB.Auto_Follow_Query.BY.Auto_Follow_Query.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Auto_Follow_Query(QueryId As Integer) As BuildQuery(Of Auto_Follow_Query)
                Get
                    Return DB.TAB.Auto_Follow_Query.BY.Auto_Follow_Query.Account_Id(Me.Id, QueryId)
                End Get
            End Property
            Public Function View_Query_AutoFollow() As BuildQuery(Of Query)
                Return DB.TAB.Query.REL.Query.Auto_Follow_Query.BY.Auto_Follow_Query.Account_Id(Me.Id) '    DB.TAB.Auto_Follow_Query.BY.Auto_Follow_Query.Account_Id(Me.Id, QueryId)
            End Function
            Public Function View_Profile_AutoFollow() As BuildQuery(Of Profile)
                Return DB.TAB.Profile.REL.Profile.auto_follow_profile.BY.Auto_Follow_Profile.Account_Id(Me.Id) '    DB.TAB.Auto_Follow_Query.BY.Auto_Follow_Query.Account_Id(Me.Id, QueryId)
            End Function


            Public ReadOnly Property Tab_Auto_Follow_Account() As BuildQuery(Of Auto_Follow_Account)
                Get
                    Return DB.TAB.Auto_Follow_Account.BY.Auto_Follow_Account.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Auto_Follow_Account(StatusType As Auto_Follow_Account.StatusType) As BuildQuery(Of Auto_Follow_Account)
                Get
                    Return DB.TAB.Auto_Follow_Account.BY.Auto_Follow_Account.Account_Id(Me.Id, StatusType)
                End Get
            End Property
            Public ReadOnly Property Tab_Auto_Follow_Account(AccFollid As Integer) As BuildQuery(Of Auto_Follow_Account)
                Get
                    Return DB.TAB.Auto_Follow_Account.BY.Auto_Follow_Account.Account_Id(Me.Id, AccFollid)
                End Get
            End Property

            Public ReadOnly Property Tab_Auto_Follow_Profile(ProfileAccountId As Integer) As BuildQuery(Of Auto_Follow_Profile)
                Get
                    Return DB.TAB.Auto_Follow_Profile.BY.Auto_Follow_Profile.Account_Id(Me.Id, ProfileAccountId)
                End Get
            End Property

            Public ReadOnly Property Tab_Auto_Follow_Profile() As BuildQuery(Of Auto_Follow_Profile)
                Get
                    Return DB.TAB.Auto_Follow_Profile.BY.Auto_Follow_Profile.Account_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property Tab_Listen_Query() As BuildQuery(Of Listen_Query)
                Get
                    Return DB.TAB.Listen_Query.BY.Listen_Query.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Listen_Query(QueryID As String) As BuildQuery(Of Listen_Query)
                Get
                    Return DB.TAB.Listen_Query.BY.Listen_Query.Account_Id(Me.Id, QueryID)
                End Get
            End Property

            Public ReadOnly Property Tab_Query_Listen() As BuildQuery(Of Query)
                Get
                    Return DB.TAB.Query.REL.Query.Listen_Query.BY.Listen_Query.Account_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property Tab_Favorite_Post() As BuildQuery(Of Favorite_Post)
                Get
                    Return DB.TAB.Favorite_Post.BY.Favorite_Post.Account_Id(Me.Id) '    Message_Post.BY.Message_Post.To_Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Favorite_Post(PostCode As String) As BuildQuery(Of Favorite_Post)
                Get
                    Return DB.TAB.Favorite_Post.BY.Favorite_Post.Account_Id(Me.Id, PostCode) '    Message_Post.BY.Message_Post.To_Account_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property Tab_Message_Post() As BuildQuery(Of Message_Post)
                Get
                    Return DB.TAB.Message_Post.BY.Message_Post.To_Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Private_Post() As BuildQuery(Of Private_Post)
                Get
                    Return DB.TAB.Private_Post.BY.Private_Post.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Private_Post_Last() As BuildQuery(Of Private_Post_Last)
                Get
                    Return DB.TAB.Private_Post_Last.BY.Private_Post_Last.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Private_Post_Last(ToAccountId As Integer, IsSend As Boolean) As BuildQuery(Of Private_Post_Last)
                Get
                    Return DB.TAB.Private_Post_Last.BY.Private_Post_Last.Account_Id(Me.Id, ToAccountId, IsSend)
                End Get
            End Property

            'Public ReadOnly Property Tab_Private_Post(issent As Integer) As BuildQuery(Of Private_Post)
            '    Get
            '        Return DB.TAB.Private_Post.BY.Private_Post.Account_Id(Me.Id, issent)
            '    End Get
            'End Property

            Public ReadOnly Property Tab_Task_Send() As BuildQuery(Of Task_Send)
                Get
                    Return DB.TAB.Task_Send.BY.Task_Send.Account_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property Tab_Share_Post() As BuildQuery(Of Share_Post)
                Get
                    Return DB.TAB.Share_Post.BY.Share_Post.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Share_Detail_to() As BuildQuery(Of Share_Detail)
                Get
                    Return DB.TAB.Share_Detail.BY.Share_Detail.To_Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Share_Detail() As BuildQuery(Of Share_Detail)
                Get
                    Return DB.TAB.Share_Detail.BY.Share_Detail.Account_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Share_Detail(PostCode As String) As BuildQuery(Of Share_Detail)
                Get
                    Return Me.Tab_Share_Detail.BY.Share_Detail.Post_Code(PostCode)
                End Get
            End Property
            Public ReadOnly Property Tab_User_Account() As BuildQuery(Of User_Account)
                Get
                    Return DB.TAB.User_Account.BY.User_Account.Account_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property _Tab_Account_Post() As BuildQuery(Of _Account_Post)
                Get
                    Dim q = New BuildQuery(Of _Account_Post)(DB, Me.ArchivePost.Table_Name)
                    Return q.BY._Account_Post._Account_Id(Me.Id) '.BY.TplAccountPost.AccountId
                End Get
            End Property

            Public ReadOnly Property _Tab_Account_Link() As BuildQuery(Of _Account_Link)
                Get
                    Dim q = New BuildQuery(Of _Account_Link)(DB, Me.ArchiveLink.Table_Name)
                    Return q.BY._Account_Link._Account_Id(Me.Id) '.BY.TplAccountPost.AccountId
                End Get
            End Property

            'Public ReadOnly Property _Tab_Link_Account(LinkType As _Account_Link.Type) As BuildQuery(Of Account)
            '    Get
            '        Dim q = New BuildQuery(Of Account)(DB, Me.ArchiveLink.Table_Name)
            '        Return q.REL._Account_Link.Account_Update.BY._Account_Link._Account_Id(Me.Id).REL._Account_Link.Account    '.BY.TplAccountPost.AccountId
            '    End Get
            'End Property

            'Public ReadOnly Property Tab_Account_Link() As BuildQuery(Of Account_Link)
            '    Get
            '        Return DB.TAB.Account_Link.BY.Account_Link.Account_Id(Me.Id)
            '    End Get
            'End Property
            Public ReadOnly Property _Tab_Account_Link(LinkType As _Account_Link.Type) As BuildQuery(Of _Account_Link)
                Get
                    Return Me._Tab_Account_Link.Where("link_type_id", "=", LinkType)
                End Get
            End Property
            Public ReadOnly Property _Tab_Account_Link(LinkType As _Account_Link.Type, FromDate As Date, toDate As Date) As BuildQuery(Of _Account_Link)
                Get
                    Return Me._Tab_Account_Link(LinkType).Where("create_date", ">=", FromDate, "create_date", "<=", toDate)
                End Get
            End Property

            Public ReadOnly Property _Tab_Account_Link(LinkType As _Account_Link.Type, AccountLinkID As Integer) As BuildQuery(Of _Account_Link)
                Get
                    Return Me._Tab_Account_Link(LinkType).Where("account_link_id", "=", AccountLinkID)
                End Get
            End Property
            Public ReadOnly Property _Tab_Account_Link_Analysis(Analysis As Boolean) As BuildQuery(Of _Account_Link)
                Get
                    Return Me._Tab_Account_Link.Where("analysis", "=", Analysis)
                End Get
            End Property


            Public ReadOnly Property _Tab_Trend() As BuildQuery(Of _Trend)
                Get
                    Dim q = New BuildQuery(Of _Trend)(DB, Me.ArchiveTrend.Table_Name)
                    Return q.BY._Trend._Account_Id(Me.Id) '.BY.TplAccountPost.AccountId
                End Get
            End Property

            Public ReadOnly Property _Tab_Trend(t As _Trend.Type) As BuildQuery(Of _Trend)
                Get
                    Return Me._Tab_Trend.Where("trend_type_id", "=", t)
                End Get
            End Property
            Public ReadOnly Property _Tab_Trend(t As _Trend.Type, D As Date) As BuildQuery(Of _Trend)
                Get
                    Return Me._Tab_Trend(t).Where("trend_date", "=", D)
                End Get
            End Property

            Public ReadOnly Property _Tab_Trend(t As _Trend.Type, FromDate As Date, toDate As Date) As BuildQuery(Of _Trend)
                Get
                    Return Me._Tab_Trend(t).Where("trend_date", ">=", FromDate, "trend_date", "<=", toDate)
                End Get
            End Property



#End Region

#Region "gestione tabella 1 - 1"

            Private _Account_Add_Info As mDB.Account_Add_Info
            Public Property Account_Add_Info() As mDB.Account_Add_Info
                Get

                    If _Account_Add_Info Is Nothing And Me.DB IsNot Nothing Then
                        _Account_Add_Info = DB.TAB.Account_Add_Info.GetByPK(Me.Id)
                    End If
                    'If _Account_Add_Info Is Nothing Then
                    '    _Account_Add_Info = DB.TAB.Account_Add_Info.GetByPK(Me.Id)
                    '    'If _Account_Add_Info Is Nothing Then
                    '    '    _Account_Add_Info = New Account_Add_Info With {.Account_Id = Me.Id}
                    '    '    DB.InsertOnSubmit(_Account_Add_Info)
                    '    '    DB.SubmitChanges()
                    '    'End If
                    'End If


                    Return _Account_Add_Info
                End Get
                Set(ByVal value As mDB.Account_Add_Info)
                    _Account_Add_Info = value
                End Set
            End Property
            Private _Account_Update As mDB.Account_Update
            Public Property Account_Update() As mDB.Account_Update
                Get

                    'If _Account_Update Is Nothing And Me.DB IsNot Nothing Then
                    '    _Account_Update = DB.TAB.Account_Update.GetByPK(Me.Id)
                    'End If
                    If _Account_Update Is Nothing Then
                        _Account_Update = DB.TAB.Account_Update.GetByPK(Me.Id)
                        If _Account_Update Is Nothing Then
                            _Account_Update = New Account_Update With {.Account_Id = Me.Id}
                            DB.InsertOnSubmit(_Account_Update)
                            DB.SubmitChanges()
                        End If
                    End If


                    Return _Account_Update
                End Get
                Set(ByVal value As mDB.Account_Update)
                    _Account_Update = value
                End Set
            End Property

            Public Function SetDefault() As mDB.Account

                Me.Account_Add_Info = New mDB.Account_Add_Info
                'Me.Account_Update = New mDB.Account_Update

                'DB.AddChangedHandle(Me)

                Return Me

            End Function

            Public Sub InsertOnSubmit(DB As mDB)

                DB.TAB.Account.InsertOnSubmit(Me)
                DB.TAB.Account_Add_Info.InsertOnSubmit(Me.Account_Add_Info)
                'DB.TAB.Account_Update.InsertOnSubmit(Me.Account_Update)

            End Sub
            Public Sub DeleteOnSubmit(DB As mDB)

                DB.TAB.Account.DeleteOnSubmit(Me)
                DB.TAB.Account_Add_Info.DeleteOnSubmit(Me.Account_Add_Info)
                'DB.TAB.Account_Update.DeleteOnSubmit(Me.Account_Update)

            End Sub

            Private Sub OnIdChanged()

                If Me.Account_Add_Info IsNot Nothing Then
                    Me.Account_Add_Info.Account_Id = Me.Id
                End If

                'If Me.Account_Update IsNot Nothing Then
                '    Me.Account_Update.Account_Id = Me.Id
                'End If

            End Sub

            Private Sub OnLocationChanged()

                If Me.Account_Add_Info IsNot Nothing Then
                    Me.Account_Add_Info.Place_Id = 0
                End If

            End Sub

            Private Sub OnFullnameChanged()

                If Me.Account_Add_Info IsNot Nothing Then
                    Me.Account_Add_Info.Gender_Type_Id = 0
                End If

            End Sub

            Private _Account_Option As Account_Option
            Public ReadOnly Property Account_Option() As Account_Option
                Get
                    If _Account_Option Is Nothing Then
                        _Account_Option = DB.TAB.Account_Option.GetByPK(Me.Id)
                        If _Account_Option Is Nothing Then
                            _Account_Option = New Account_Option With {.Account_Id = Me.Id}
                            DB.InsertOnSubmit(_Account_Option)
                            DB.SubmitChanges()
                        End If
                    End If
                    Return _Account_Option
                End Get
            End Property

            'Private _Account_Elaboration As Account_Elaboration
            'Public ReadOnly Property Account_Elaboration() As Account_Elaboration
            '    Get
            '        If _Account_Elaboration Is Nothing Then
            '            _Account_Elaboration = DB.TAB.Account_Elaboration.GetByPK(Me.Id)
            '            If _Account_Elaboration Is Nothing Then
            '                _Account_Elaboration = New Account_Elaboration With {.Account_Id = Me.Id}
            '                DB.InsertOnSubmit(_Account_Elaboration)
            '                DB.SubmitChanges()
            '            End If
            '        End If
            '        Return _Account_Elaboration
            '    End Get
            'End Property

            Private _Account_Auth As Account_Auth
            Public ReadOnly Property Account_Auth() As Account_Auth
                Get
                    If _Account_Auth Is Nothing Then
                        _Account_Auth = DB.TAB.Account_Auth.GetByPK(Me.Id)
                    End If
                    Return _Account_Auth
                End Get
            End Property

#End Region

#Region "OAUTH"

            Public Function GetOauth() As WebApi.Oauth.Oauth

                'Return Me.Tab_User_Account.BY.User_Account.Enabled.Limit(1).ToObj.getOauth
                If Me.Account_Auth.Disabled = 0 Then
                    Return Me.Account_Auth.getOauth
                Else
                    Return Nothing
                End If


            End Function
            Public Function GetOauth2() As WebApi.Oauth.Oauth2

                'Return Me.Tab_User_Account.BY.User_Account.Enabled.Limit(1).ToObj.getOauth2
                If Me.Account_Auth.Disabled = 0 Then
                    Return Me.Account_Auth.getOauth2
                Else
                    Return Nothing
                End If


            End Function

#End Region

#Region "LINK"

            Public Shared Function GetForUpdate(AccountCode As String, net As MyApp.Network.AccType) As Account
                Dim db = mDB.GetDB

                Dim NewAcc = db.TAB.Account.BY.Account.Account_Code(AccountCode).ToObj
                If NewAcc Is Nothing Then
                    NewAcc = (New mDB.Account).SetDefault
                    NewAcc.Network_Id = net
                    NewAcc.Account_Code = AccountCode

                    'db.TAB.Account.InsertOnSubmit(NewAcc)

                    NewAcc.InsertOnSubmit(db)

                    'DB.SubmitChanges()
                End If


                Return NewAcc

            End Function
            Public Function AddAccountLink(LinkType As _Account_Link.Type, AccountCode As String, net As MyApp.Network.AccType) As _Account_Link

                '-------------------------------------------------------------
                'crea l'account
                Dim NewAcc = GetForUpdate(AccountCode, net)
                DB.SubmitChanges()


                '-------------------------------------------------------------
                'crea/aggiona il link
                Dim AccLink = Me._Tab_Account_Link(LinkType, NewAcc.Id).ToObj
                If AccLink Is Nothing Then
                    AccLink = New mDB._Account_Link With {
                        .Account_Id = Me.Id,
                        .Account_Link_Id = NewAcc.Id,
                        .Link_Type_Id = LinkType,
                        .Create_Date = Date.UtcNow
                    }
                    DB.InsertOnSubmit(Me.ArchiveLink.Table_Name, AccLink)

                    If Me.Id = MyApp.AccountDebug Then
                        MyApp.WriteProcLog(SF("(tab)(tab)update followers add link: {0} - {1}", LinkType, AccountCode), MyApp.Task.TaskType.DEBUG)
                    End If

                End If

                AccLink.Updating = 1
                DB.SubmitChanges()

                '-------------------------------------------------------------
                'elimino l'eventuale stato opposto
                Dim res = Me._Tab_Account_Link(_Account_Link.GetOldLinkType(LinkType), NewAcc.Id).
                    Delete.
                ExecuteCommand()

                '---------------------------------------------
                ' DEBUG
                '---------------------------------------------
                If Me.Id = MyApp.AccountDebug And res > 0 Then
                    MyApp.WriteProcLog(SF("(tab)(tab)update followers remove old link: {0} - {1}", _Account_Link.GetOldLinkType(LinkType), AccountCode), MyApp.Task.TaskType.DEBUG)
                End If

                Return AccLink

            End Function
            Public Function RemoveAccountLink(LinkType As _Account_Link.Type, AccountCode As String) As _Account_Link

                Dim FollAcc = DB.TAB.Account.BY.Account.Account_Code(AccountCode).ToObj
                Dim AccLink As _Account_Link = Nothing

                If FollAcc IsNot Nothing Then
                    AccLink = Me._Tab_Account_Link(LinkType, FollAcc.Id).ToObj '   DB.TAB.Account_Link.GetByPKs(Me.Id, LinkType, FollAcc.Id)
                    If AccLink IsNot Nothing Then
                        DB.DeleteOnSubmit(Me.ArchiveLink.Table_Name, AccLink)

                        Dim NewAccLink = AccLink.Clone
                        NewAccLink.Link_Type_Id = _Account_Link.GetOldLinkType(LinkType)
                        NewAccLink.Create_Date = Date.UtcNow
                        NewAccLink.Updating = False
                        NewAccLink.Analysis = False
                        DB.InsertOnSubmit(Me.ArchiveLink.Table_Name, NewAccLink)
                        DB.SubmitChanges()
                    End If
                End If

                Return AccLink

            End Function

            Public Sub SetAccountLinkStatusFollower()

                '---------------------------------------------
                ' DEBUG
                '---------------------------------------------
                If Me.Id = MyApp.AccountDebug Then
                    Dim acclinkold = Me._Tab_Account_Link(_Account_Link.Type.FOLLOWER).
                        REL._Account_Link.Account.
                        Where("updating", "=", False).SetSelect("account.account_code").
                    ToList(Of String)("account_code")

                    For Each acccode In acclinkold
                        MyApp.WriteProcLog(SF("(tab)(tab)update followers become old: {0} ", acccode), MyApp.Task.TaskType.DEBUG)
                    Next

                End If

                '---------------------------------------------
                ' i follower che non si sono aggionati li faccio diventare old follower
                Dim res1 = Me._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                    Where("updating", "=", False).
                    Update.
                    UpdateValue("link_type_id", mDB._Account_Link.Type.FOLLOWER_OLD).
                    UpdateValue("create_date", Date.UtcNow).
                    UpdateValue("analysis", False).
                ExecuteCommand()

                '---------------------------------------------
                ' reimposto updating a 0 per i follower con un limite massimo
                Dim TotFollLink = Me._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                    Update.
                    UpdateValue("updating", 0).
                ExecuteCommand()




                '---------------------------------------------
                ' DEBUG
                '---------------------------------------------
                If Me.Id = MyApp.AccountDebug Then
                    MyApp.WriteProcLog(SF("(tab)(tab)update followers update data: become old: {0} - reset foll updating: {1}", res1, TotFollLink), MyApp.Task.TaskType.DEBUG)
                End If

                '---------------------------------------------
                'aggiorno i follower per l'analisi
                If Me.Account_Auth.Analysis_Followers Then

                    ' tutti quelli che non sono foll metto analisi = falso
                    'Me.Tab_Account_Link.
                    '    Where("link_type_id", "<>", mDB.Account_Link.Type.FOLLOWER).
                    '    Update.
                    '    UpdateValue("analysis", False).
                    'ExecuteCommand()

                    MyApp.WriteProcLog(SF("(tab)(tab)update followers: set not foll analysis = false"), MyApp.Task.TaskType.UPDATE_ACCOUNTS)

                    If Me.Account_Auth.Analysis_Followers_Limit = 0 Then

                        'se devono essere analizzati tutti
                        Me._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                            Update.
                            UpdateValue("analysis", True).
                        ExecuteCommand()

                        MyApp.WriteProcLog(SF("(tab)(tab)update followers: set all foll analysis = true"), MyApp.Task.TaskType.UPDATE_ACCOUNTS)

                    Else

                        Dim TotAnalysis = Me._Tab_Account_Link_Analysis(True).SetSelect("count(*)").ToObj(Of Integer)()
                        Dim MaxAccAna As Integer = Me.Account_Auth.Analysis_Followers_Limit * 1.1
                        Dim Addanalysis As Boolean
                        Dim acclinks = New List(Of mDB._Account_Link)

                        ' se mancano li aggiunge
                        If TotAnalysis < Me.Account_Auth.Analysis_Followers_Limit And TotAnalysis < TotFollLink Then
                            Addanalysis = True

                            acclinks = Me._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                                Where("analysis", "=", False).
                                Limit(MaxAccAna - TotAnalysis).
                            ToList

                        End If

                        'se sono troppi li toglie
                        If TotAnalysis > MaxAccAna Then
                            Addanalysis = False
                            acclinks = Me._Tab_Account_Link(mDB._Account_Link.Type.FOLLOWER).
                                Where("analysis", "=", True).
                                Limit(TotAnalysis - MaxAccAna).
                            ToList

                        End If

                        If acclinks.Count > 0 Then
                            MyApp.WriteProcLog(SF("(tab)(tab)update followers: addanalysis = {0}, count: {1}", Addanalysis, acclinks.Count), MyApp.Task.TaskType.UPDATE_ACCOUNTS)

                            For Each acclink In acclinks
                                acclink.Analysis = Addanalysis
                                DB.SubmitChanges()
                            Next

                        End If

                    End If
                End If

                'aggiorno il linkupdate
                Me.Account_Update.Follower_Last_Code = ""
                Me.Account_Update.Follower_Update = Date.UtcNow
                Me.Account_Update.Follower_Update_Count = Me.Account_Add_Info.Follower_Count

                DB.SubmitChanges()


            End Sub
            Public Sub SetAccountLinkStatusFriend()

                ' mofifico in old friend
                Me._Tab_Account_Link(mDB._Account_Link.Type.FRIENDS).
                    Where("updating", "=", False).
                    Update.
                    UpdateValue("link_type_id", mDB._Account_Link.Type.FRIEND_OLD).
                    UpdateValue("create_date", Date.UtcNow).
                ExecuteCommand()

                'imposto gli aggiornati a 0
                Me._Tab_Account_Link(mDB._Account_Link.Type.FRIENDS).
                    Update.
                    UpdateValue("updating", 0).
                ExecuteCommand()

                'aggiorno il linkupdate
                Me.Account_Update.Friend_Last_Code = ""
                Me.Account_Update.Friend_Update = Date.UtcNow
                Me.Account_Update.Friend_Update_Count = Me.Account_Add_Info.Friend_Count

                DB.SubmitChanges()

            End Sub

            'Public Function GetConnection(Codes As List(Of String), linksType() As Account_Link.Type) As List(Of Connect)

            '    Dim Conn As New List(Of Connect)

            '    For Each lt In linksType
            '        Dim t = lt
            '        Conn.AddRange(
            '            DB.TAB.Account.
            '            REL.Account.Account_Link.
            '            BY.Account_Link.Account_Id(Me.Id, t).
            '            Where("account_code", "IN", Codes).
            '            ToList.
            '            Select(Function(o) New Connect With {
            '                .AccountCode = o.Account_Code, .Type = t
            '            })
            '        )

            '    Next

            '    Return Conn

            'End Function
            'Public Function GetConnection(Ids As List(Of Integer), linksType() As Account_Link.Type) As List(Of Connect)

            '    Dim Conn As New List(Of Connect)


            '    For Each lt In linksType
            '        Dim t = lt
            '        Conn.AddRange(
            '            Me.Tab_Account_Link(t).
            '            Where("account_link_id", "IN", Ids).
            '            ToList.
            '            Select(Function(o) New Connect With {
            '                .AccountId = o.Account_Link_Id, .Type = t
            '            })
            '        )

            '    Next

            '    Return Conn

            'End Function
            'Public Function GetConnection(Codes As List(Of String), Ids As List(Of Integer), linksType() As Account_Link.Type) As List(Of Connect)

            '    Dim Conn As New List(Of Connect)

            '    For Each lt In linksType
            '        Dim t = lt
            '        Dim q = DB.TAB.Account.
            '            REL.Account.Account_Link.
            '            BY.Account_Link.Account_Id(Me.Id, t)

            '        If Codes Is Nothing Then
            '            q.Where("account_link_id", "IN", Ids)
            '        Else
            '            q.Where("account_code", "IN", Codes)
            '        End If

            '        Conn.AddRange(q.ToList.
            '            Select(Function(o) New Connect With {
            '                .AccountId = o.Id, .AccountCode = o.Account_Code, .Type = t
            '            })
            '        )

            '    Next

            '    Return Conn

            'End Function

            Public Function View_AccountLink(Codes As List(Of String), Ids As List(Of Integer), linksType As _Account_Link.Type) As BuildQuery(Of _Account_Link)

                'Dim q = DB.TAB.Account.
                '        REL.Account.Account_Link.
                '        BY.Account_Link.Account_Id(Me.Id, linksType)

                Dim q = Me._Tab_Account_Link(linksType).
                    REL._Account_Link.Account


                If Codes Is Nothing Then
                    q.Where("account_link_id", "IN", Ids)
                Else
                    q.Where("account_code", "IN", Codes)
                End If

                Return q

            End Function

            'Public Function GetConnection(Codes As List(Of String), Ids As List(Of Integer), linksType() As Account_Link.Type) As Connects

            '    Dim Conn As New Connects

            '    Dim TotCod = 0
            '    If Codes IsNot Nothing Then
            '        TotCod = Codes.Count
            '    End If
            '    If Ids IsNot Nothing Then
            '        TotCod = Ids.Count
            '    End If

            '    If TotCod > 0 Then
            '        For Each lt In linksType
            '            'Dim t = lt
            '            Dim q = DB.TAB.Account.
            '                REL.Account.Account_Link.
            '                BY.Account_Link.Account_Id(Me.Id, lt)

            '            If Codes Is Nothing Then
            '                q.Where("account_link_id", "IN", Ids)
            '            Else
            '                q.Where("account_code", "IN", Codes)
            '            End If

            '            For Each Acc In q.ToList
            '                If Not Conn.ContainsKey(Acc.Account_Code) Then
            '                    Conn.Add(Acc.Account_Code, New Connect)
            '                End If
            '                Conn(Acc.Account_Code).Types.Add(lt, True)
            '                Conn(Acc.Account_Code).Account = Acc
            '            Next

            '            'Conn.AddRange(q.ToList.
            '            '    Select(Function(o) New Connect With {
            '            '        .AccountId = o.Id, .AccountCode = o.Account_Code, .Type = t
            '            '    })
            '            ')

            '        Next
            '    End If

            '    Return Conn

            'End Function

            'Public Class Connect
            '    Property Account As Account
            '    Property Types As New Dictionary(Of Account_Link.Type, Boolean)
            'End Class
            'Public Class Connects
            '    Inherits Dictionary(Of String, Connect)

            'End Class


            'Public Class Connect2
            '    Property Type As New Dictionary(Of Account_Link.Type, Boolean)
            'End Class

            Public Function GetAccountLinkCount(t As _Account_Link.Type, fromDate As Date, ToDate As Date) As Integer

                Return Me._Tab_Account_Link(t, fromDate, ToDate).SetSelect("count(*)").ToObj(Of Integer)()

            End Function

            Public Function GetInterractionAccount(FromDate As Date, Todate As Date) As Dictionary(Of Integer, Integer)
                Dim InterAccs As New Dictionary(Of Integer, Integer)
                Dim dt As DataTable

                dt = Me.Tab_Message_Post.
                    Where("pubb_date", ">=", FromDate, "pubb_date", "<", Todate).
                    GroupBy("account_id").
                    OrderBy("Total desc").
                    SetSelect("account_id", "Count(account_id) as Total").
                    Limit(100).
                ToDataTable

                SumInterAccount(dt, InterAccs)

                'dt = Me.Tab_Share_Post.
                '    REL.Share_Post.Share_Detail.
                '    Where("share_detail.pubb_date", ">", FromDate, "share_detail.pubb_date", "<=", Todate).
                '    GroupBy("share_detail.account_id").
                '    OrderBy("Total desc").
                '    SetSelect("share_detail.account_id", "Count(share_detail.account_id) as Total").
                '    Limit(100).
                'ToDataTable
                dt = Me.Tab_Share_Detail_to.
                    Where("share_detail.pubb_date", ">", FromDate, "share_detail.pubb_date", "<=", Todate).
                    GroupBy("share_detail.account_id").
                    OrderBy("Total desc").
                    SetSelect("share_detail.account_id", "Count(share_detail.account_id) as Total").
                    Limit(100).
                ToDataTable


                SumInterAccount(dt, InterAccs)

                Return InterAccs

            End Function
            Private Sub SumInterAccount(dt As DataTable, Accs As Dictionary(Of Integer, Integer))

                For Each dr As DataRow In dt.Rows

                    Dim Key = dr("account_id")

                    If Accs.ContainsKey(Key) Then
                        Accs(Key) += dr("total")
                    Else
                        Accs.Add(Key, dr("total"))
                    End If

                Next

            End Sub

            Dim MaxAccountUpdate As Integer = 2000
            Public Function View_Follower_Block(Field As String) As BuildQuery(Of _Account_Link)
                Dim qfoll = Me._Tab_Account_Link(_Account_Link.Type.FOLLOWER).
                    Where("account_link_id", ">", DB.GetFieldValue(Me.Account_Update, Field)).
                    OrderBy("account_link_id").
                Limit(MaxAccountUpdate + 1)

                Return qfoll

            End Function
            Public Function SetFieldFollowerBlock(Field As String) As Integer

                Dim lastid As Integer = 0

                Dim dtlastfoll = DB.GetQuery.From(Me.View_Follower_Block(Field), "Account_Link", "").
                    SetSelect("max(account_link_id) as maxid, count(account_link_id) as count").ToDataTable

                If dtlastfoll(0)("count") > MaxAccountUpdate Then
                    lastid = dtlastfoll(0)("maxid")
                End If

                DB.SetFieldValue(Me.Account_Update, Field, lastid)

                Return lastid

            End Function

#End Region

#Region "FOLLOWERS"

            Public Sub ResetFollowerAnalysis(AnalysisType As Follower_Analysis.Type)

                Me.Tab_Follower_Analysis(AnalysisType).Delete.ExecuteCommand()

            End Sub

            Public Sub SetFollowerAnalysis(AnalysisType As Follower_Analysis.Type, DataType As Integer, Value As Integer)

                Dim Analysis = Me.Tab_Follower_Analysis(AnalysisType, DataType).ToObj
                If Analysis Is Nothing Then
                    Analysis = New mDB.Follower_Analysis With {
                        .Account_Id = Me.Id,
                        .Analysis_Type_Id = AnalysisType,
                        .Data_Type_Id = DataType
                    }

                    DB.TAB.Follower_Analysis.InsertOnSubmit(Analysis)
                End If

                Analysis.Value = Value

                DB.SubmitChanges()

            End Sub
            Public Function GetFollowerAnalysisValue(AnalysisType As Follower_Analysis.Type, DataType As Integer) As Integer

                Dim Analysis = Me.Tab_Follower_Analysis(AnalysisType, DataType).ToObj
                If Analysis Is Nothing Then
                    Return 0
                Else
                    Return Analysis.Value
                End If

            End Function
            Public Function GetFollowerAnalysis(AnalysisType As Follower_Analysis.Type) As List(Of Follower_Analysis)

                Return Me.Tab_Follower_Analysis(AnalysisType).ToList

            End Function

#End Region

#Region "POST"

            Public Sub DownloadAccountEngadment(Reload As Boolean)

                If Me.Account_Update.Message_Post_Update < Date.UtcNow.AddSeconds(-60 * 2) Or Reload Then

                    Dim tw = New MyApp.Network.Twitter(Me.GetOauth)
                    tw.DownloadAccountMessagePosts(Me)

                    tw.DownloadAccountFavoritePosts(Me)
                    'tw.DownloadAccountShares(CurrAccount)
                    tw.DownloadAccountPrivatePosts(Me)
                    tw.DownloadAccountPosts(Me, GloukDB.Account.UpdatePostMode.FOLLOWER)

                    'IMPORTANTE sarebbbe da ottimizare solo per l'account
                    MyApp.Task.Update.AccountMessagesConversations()

                    MyApp.Task.Update.AccountAccountsUpdate(New List(Of mDB.Account) From {Me}, GloukDB.Account.UpdateAccountMode.ENGAGEMENT)

                End If

            End Sub
            Public Function DownloadAccountHashTag() As Boolean

                Dim ids = Me.Tab_Listen_Query.
                    REL.Listen_Query.Query.
                    Where("listen_disabled_view", "=", False).
                    SetSelect("query_id").
                ToList(Of Integer)("query_id")

                If ids.Count > 0 Then
                    MyApp.Task.Update.QueryPostsUpdate(ids, Query.UpdateModeType.REALTIME)

                End If


                Return ids.Count > 0


            End Function


            Public Function GetLastFavoritePostCode() As String

                Dim LastPost = Me.GetLastFavoritePost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost.Post_Code
                Else
                    Return ""
                End If

            End Function
            Public Function GetLastFavoritePost() As mDB.Favorite_Post

                Dim LastMess = Me.Tab_Favorite_Post.OrderBy("pubb_date desc").Limit(1).ToObj
                'prendo il messaggio + nuovo
                If LastMess IsNot Nothing Then
                    Return LastMess
                Else
                    Return Nothing
                End If

            End Function

            Public Function GetLastMessagePost() As mDB.Message_Post

                Dim LastMess = Me.Tab_Message_Post.OrderBy("pubb_date desc").Limit(1).ToObj
                'prendo il messaggio + nuovo
                If LastMess IsNot Nothing Then
                    Return LastMess
                Else
                    Return Nothing
                End If

            End Function
            Public Function GetLastMessagePostCode() As String

                Dim LastPost = Me.GetLastMessagePost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost.Post_Code
                Else
                    Return ""
                End If

            End Function
            Public Function GetLastMessagePostDateUniversalTimeStamp() As String

                Dim LastPost = Me.GetLastMessagePost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return Utils.Conv.ToTimeStamp(LastPost.Pubb_Date.ToUniversalTime).ToString
                Else
                    Return ""
                End If

            End Function

            Public Function GetLastPrivatePost(sent As Boolean) As mDB.Private_Post

                Dim LastMess = Me.Tab_Private_Post.Where("is_sent", "=", sent).OrderBy("pubb_date desc").Limit(1).ToObj
                'prendo il messaggio + nuovo
                If LastMess IsNot Nothing Then
                    Return LastMess
                Else
                    Return Nothing
                End If

            End Function
            Public Function GetLastPrivatePostCode(sent As Boolean) As String

                Dim LastPost = Me.GetLastPrivatePost(sent)

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost.Post_Code
                Else
                    Return ""
                End If

            End Function

            Public Function GetLastPost() As mDB._Account_Post

                Dim LastPost = Me._Tab_Account_Post.OrderBy("pubb_date desc").Limit(1).ToObj
                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost
                Else
                    Return Nothing
                End If


            End Function
            Public Function GetLastPostCode() As String

                Dim LastPost = Me.GetLastPost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost.Post_Code
                Else
                    Return ""
                End If

            End Function
            Public Function GetLastPostDateUniversalTimeStamp() As String

                Dim LastPost = Me.GetLastPost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return Utils.Conv.ToTimeStamp(LastPost.Pubb_Date.ToUniversalTime).ToString
                Else
                    Return ""
                End If

            End Function

            Private _ArchivePost As mDB.Archive_Data
            Public ReadOnly Property ArchivePost As mDB.Archive_Data
                Get
                    If _ArchivePost Is Nothing Then
                        _ArchivePost = Archive_Data.GetUpdateArchine(DB, Me, Archive_Data.Type.ACCOUNT_POST, "Archive_Post_Id")
                    End If
                    Return _ArchivePost

                End Get
            End Property

            Private _ArchiveTrend As mDB.Archive_Data
            Public ReadOnly Property ArchiveTrend As mDB.Archive_Data
                Get
                    If _ArchiveTrend Is Nothing Then
                        _ArchiveTrend = Archive_Data.GetUpdateArchine(DB, Me.Account_Update, Archive_Data.Type.ACCOUNT_TREND, "Archive_Trend_Id")
                    End If
                    Return _ArchiveTrend

                End Get
            End Property

            Private _ArchiveLink As mDB.Archive_Data
            Public ReadOnly Property ArchiveLink As mDB.Archive_Data
                Get
                    If _ArchiveLink Is Nothing Then
                        _ArchiveLink = Archive_Data.GetUpdateArchine(DB, Me.Account_Update, Archive_Data.Type.ACCOUNT_LINK, "Archive_Link_Id")
                    End If
                    Return _ArchiveLink
                End Get
            End Property


#End Region

#Region "ACTIVITY"

            Public Function GetActivityHours() As Integer()

                Return Me.Account_Add_Info.Post_Hours 'mDB.Account.GetActivityHours(Me.Account_Add_Info.Post_Hours)

            End Function
            Public Shared Function GetActivityHours(Post_Hours_Json As String) As Integer()

                Dim i(23) As Integer
                Return MyApp.JSONDeserialize(Of Integer())(Post_Hours_Json, i)

                'If Post_Hours.Trim = "" Then
                '    Dim i(23) As Integer
                '    Return i
                'Else

                '    Return MyApp.JSONDeserialize(Of Integer())(Post_Hours)
                'End If

            End Function
            Public Sub SetActivity(dates As List(Of Date))

                '-------------------------------------
                'ORE

                If dates.Count > 0 Then

                    Dim FollHours = Me.Account_Add_Info.Post_Hours
                    Dim PreTot = FollHours.Sum

                    For Each d In dates
                        FollHours(Me.LDate(d).Hour) += 1
                    Next

                    Dim PostTot = FollHours.Sum

                    Me.Account_Add_Info.Post_Hours_Total = PostTot
                    Me.Account_Add_Info.Post_Hours = FollHours ' MyApp.JSONSerialize(FollHours)

                    If Math.Floor(PreTot / 200) <> Math.Floor(PostTot / 200) Then
                        Me.Account_Add_Info.Business_Type_Id = mDB.Account.BusinessType.NOT_ASSIGNED
                    End If

                    ' IDEAA qundo suoerano tipo i 1000/2000 post si riproporziaona tutto a 300.. poi in modo naturale rifarà il conteggio quando risale e supera i 400

                    '-------------------------------------
                    'SETTIMANE

                    Dim FollWeeks = Me.Account_Add_Info.Post_Weeks

                    Me.Account_Add_Info.Status_Type_Id = mDB.Account.StatusType.NOT_ASSIGNED
                    Me.Account_Add_Info.Post_Weeks = Me.UpdateWeekActivity(FollWeeks, dates)

                    DB.SubmitChanges()

                End If


            End Sub
            Public Function UpdateWeekActivity(FollWeeks As Dictionary(Of String, Integer), dates As List(Of Date)) As Dictionary(Of String, Integer)

                For Each d In dates
                    Dim NWeek = DateDiff(DateInterval.WeekOfYear, New Date(2000, 1, 1), d, FirstDayOfWeek.Monday)
                    If Not FollWeeks.ContainsKey(NWeek) Then
                        FollWeeks.Add(NWeek, 0)
                    End If
                    FollWeeks(NWeek) += 1
                Next

                Dim weekmin = DateDiff(DateInterval.WeekOfYear, New Date(2000, 1, 1), Date.UtcNow, FirstDayOfWeek.Monday)
                Dim keys = FollWeeks.Keys.ToArray
                For ct = 0 To keys.Count - 1
                    If CInt(keys(ct)) < weekmin - 4 Then
                        FollWeeks.Remove(keys(ct))
                    End If
                Next

                Return FollWeeks

            End Function
            Public Function CalculateActivityCoeff() As Double

                Return mDB.Account.CalculateActivityCoeff(Me.GetActivityHours) 'Me.GetActivityHours)

            End Function
            Public Shared Function CalculateActivityCoeff_old(FollHours() As Integer) As Double

                'Dim FollHours = Me.GetActivityHours

                'calcolo indice cons
                Dim media = FollHours.Average
                Dim totdiff = 0
                For ct = 1 To FollHours.Length - 1
                    totdiff += Math.Abs(FollHours(ct) - FollHours(ct - 1))
                Next
                Dim mediadiff = totdiff / (FollHours.Length - 1)

                Return Utils.Math.Div(mediadiff, media)


            End Function
            Public Shared Function CalculateActivityCoeff(FollHours() As Integer) As Double

                'calcolo indice cons
                Dim tot = FollHours.Sum

                Dim TotCons = 0
                For ct = 0 To 7
                    TotCons += FollHours(ct)
                Next
                For ct = 18 To 23
                    TotCons += FollHours(ct)
                Next

                Return Utils.Math.Div(TotCons, tot)

            End Function

            'Public Sub SetActivityWeek(dates As List(Of Date))

            '    Dim FollHours = Me.Account_Add_Info.Post_Weeks
            '    Dim PreTot = FollHours.Sum

            '    For Each d In dates
            '        FollHours(d.Hour) += 1
            '    Next

            '    Dim PostTot = FollHours.Sum

            '    Me.Account_Add_Info.Post_Hours_Total = PostTot
            '    Me.Account_Add_Info.Post_Hours = MyApp.JSONSerialize(FollHours)

            '    If Math.Floor(PreTot / 200) <> Math.Floor(PostTot / 200) Then
            '        Me.Account_Add_Info.Business_Type_Id = mDB.Account.BusinessType.NOT_ASSIGNED
            '    End If

            '    ' IDEAA qundo suoerano tipo i 1000/2000 post si riproporziaona tutto a 300.. poi in modo naturale rifarà il conteggio quando risale e supera i 400

            '    DB.SubmitChanges()

            'End Sub

#End Region

#Region "UI"

            Public Shared Function PrintGender(g As Gender_Name.Type) As String

                Select Case g
                    Case Gender_Name.Type.UNKNOW
                        Return "-"

                    Case Else

                        Return g.ToString
                End Select


            End Function

            Private _print As MyUI.Print2
            Public Property Print() As MyUI.Print2
                Get
                    If _print Is Nothing Then
                        _print = New MyUI.Print2(Me.Utc_Offset)
                    End If
                    Return _print
                End Get
                Set(ByVal value As MyUI.Print2)
                    _print = value
                End Set
            End Property



#End Region

#Region "Date"

            ' trasforma una data in UTC in data loclale dell utente
            Public Function LDate(UtcDate As Date) As Date
                Return UtcDate.AddSeconds(Me.Utc_Offset)
            End Function
            ' trasforma una data loclale dell utente in UTC in data 
            Public Function UtcDate(LDate As Date) As Date
                Return LDate.AddSeconds(-Me.Utc_Offset)
            End Function

            Public Function LTime(UtcDate As TimeSpan) As TimeSpan
                Return UtcDate.Add(New TimeSpan(0, 0, Me.Utc_Offset))

            End Function
            Public Function UtcTime(LDate As TimeSpan) As TimeSpan
                Return LDate.Add(New TimeSpan(0, 0, -Me.Utc_Offset))
            End Function

#End Region
#Region "TRENDS"

            Public Function GetTrendSum(t As _Trend.Type, fromDate As Date, ToDate As Date) As Integer

                Return Me._Tab_Trend(t, fromDate, ToDate).SetSelect("sum(value)").ToObj(Of Integer)()

            End Function

            Public Function GetTrendValue(t As _Trend.Type, D As Date) As Integer

                Return Me._Tab_Trend(t, D).SetSelect("value").ToObj(Of Integer)()

            End Function
            Public Function GetTrend(t As _Trend.Type, FromDate As Date, ToDate As Date, groupby As DateInterval) As List(Of _Trend)

                Dim q = Me._Tab_Trend(t, FromDate, ToDate)

                Select Case groupby
                    Case DateInterval.Day
                        q.
                            SetSelect("trend_date", "value")

                    Case DateInterval.Weekday

                        q.
                            GroupBy("YEARWEEK(trend_date)").
                            SetSelect("trend_date", "sum(value) as value")
                End Select


                Return q.ToList

            End Function

            Public Function AddTrend(t As _Trend.Type, D As Date, value As Object, update As Boolean) As Boolean
                Dim Trend = Me._Tab_Trend(t, D).ToObj  '   DB.TAB.Trend.BY.Trend.Account_Id(Acc.Id, mDB.Trend.Type.FOLLOWER_ABS, Today).ToObj
                Dim v As Object = value

                If Trend Is Nothing Or update Then
                    If value.GetType <> GetType(Integer) Then
                        v = value.ToObj(Of Integer)()
                    End If
                End If

                If Trend Is Nothing Then

                    Trend = New mDB._Trend With {
                        .Account_Id = Me.Id,
                        .Trend_Type_Id = t,
                        .Trend_Date = D,
                        .Value = v
                    }
                    DB.InsertOnSubmit(Me.ArchiveTrend.Table_Name, Trend)
                    DB.SubmitChanges()

                    Return True

                Else
                    If update Then
                        Trend.Value = v
                        DB.SubmitChanges()

                    End If

                    Return False

                End If


            End Function

            Public Function AddTrend(t As _Trend.Type, D As Date, value As Object) As Boolean

                Return Me.AddTrend(t, D, value, False)

            End Function


#End Region


#Region "AUTO_FOLL"

            Public Function CheckAddAutoFollAccount(AccID As Integer, ByRef CountFoll As Integer) As Boolean

                'IMPORTANTE inserisce un account da seguire anche se esiste già e non viene toccato da da almeno 6 mesi
                Dim AddAutoFoll = False
                CountFoll = 0

                Dim link = Me._Tab_Account_Link(_Account_Link.Type.FRIENDS, AccID).ToObj

                If link Is Nothing Then
                    Dim FollAccs = DB.TAB.Auto_Follow_Account.BY.Auto_Follow_Account.Account_Id(Me.Id, AccID).ToList
                    CountFoll = FollAccs.Count
                    If CountFoll = 0 Then
                        AddAutoFoll = True
                    Else
                        Dim FollAcc = FollAccs.OrderByDescending(Function(o) o.Update_Status_Date).First
                        If FollAcc.Update_Status_Date < Date.UtcNow.AddMonths(-6) And FollAcc.Source_Type_Id = mDB.Auto_Follow_Account.StatusType.UNFOLLOW Then
                            AddAutoFoll = True
                        End If
                    End If

                End If

                Return AddAutoFoll

            End Function

            Public Function GetFriendCount(day As Integer) As Integer

                Return Me.Tab_Auto_Follow_Account.Where("follow_date", ">", Date.UtcNow.AddDays(-day)).SetSelect("count(*) as Tot").ToObj(Of Integer)()

            End Function
            Public Function GetUnfollowCount(day As Integer) As Integer

                Return Me.Tab_Auto_Follow_Account.Where("unfollow_date", ">", Date.UtcNow.AddDays(-day)).SetSelect("count(*) as Tot").ToObj(Of Integer)()

            End Function


#End Region



            Public Function AddFavoritePost(PostCode As String) As Favorite_Post



                'Dim Favorite = mDB.Favorite_Post.GetForUpdate(Me.Id, PostCode)
                'DB.SubmitChanges()

                Dim Favorite = MyApp.Task.Send.AddFavotirePost(Me, PostCode)

                Return Favorite

            End Function

            Public Sub RemoveFavoritePost(PostCode As String)

                MyApp.Task.Send.RemoveFavotirePost(Me, PostCode)

                Me.Tab_Favorite_Post(PostCode).Delete.ExecuteCommand()

            End Sub

            Public Sub AddPostShare(SharePostCode As String)

                Dim share = MyApp.Task.Send.SendPost(Me, New mDB.Task_Post With {.Share_Post_Code = SharePostCode, .Post_Type_Id = mDB.Task_Post.Type.SHARE})

                'Dim Share = mDB.Share_Post.GetForUpdate(SharePostCode)
                'DB.SubmitChanges()

                'Dim ShareDett = New mDB.Share_Detail With {
                '    .Account_Id = Me.Id,
                '    .Post_Code = NewPostCode,
                '    .Share_Post_Id = Share.Id,
                '    .Pubb_Date = Date.UtcNow
                '}

                'DB.TAB.Share_Detail.InsertOnSubmit(ShareDett)

                'DB.SubmitChanges()

            End Sub

            Public Sub RemoveSharePost(PostCode As String)

                Dim post = MyApp.Task.Send.RemovePost(Me, PostCode, Task_Post.Type.SHARE)

                Dim Share = DB.TAB.Share_Post.BY.Share_Post.Post_Code(PostCode).ToObj
                Share.Tab_Share_Detail.BY.Share_Detail.Account_Id(Me.Id).Delete.ExecuteCommand()

                'DB.TAB.Share_Detail.DeleteOnSubmit(GetShareDettFromPost(PostCode))
                'DB.SubmitChanges()

                Me.Tab_Share_Detail(PostCode).Delete.ExecuteCommand()

            End Sub
            Public Function GetShareDettFromPost(PostCode As String) As mDB.Share_Detail

                Dim Share = DB.TAB.Share_Post.BY.Share_Post.Post_Code(PostCode).ToObj
                If Share IsNot Nothing Then
                    Return Share.Tab_Share_Detail.BY.Share_Detail.Account_Id(Me.Id).ToObj
                Else
                    Return Nothing
                End If

            End Function

            Public Sub AddPrivatePost(post As mDB.Task_Post)

                post.Task_Send_Id = mDB.Task_Post.Type.PRIVATE
                Dim Mess = MyApp.Task.Send.SendPost(Me, post)

            End Sub

            Public Sub RemovePrivatePost(id As String)



            End Sub

            Public Function GetDateMinUpdate() As Date

                Dim dd As New List(Of Date)
                dd.Add(Me.Account_Update.Message_Post_Update)
                dd.Add(Me.Account_Update.Private_Post_Update)
                dd.Add(Me.Account_Update.Share_Det_Update)

                Dim Datamin = dd.Min
                If Datamin = Date.MinValue Then
                    Datamin = Date.UtcNow.AddYears(-1)
                End If

                Return Datamin

            End Function




#Region "FILTER"

            Public Function View_AccountLink_ByFilter(f As Filter) As BuildQuery(Of mDB._Account_Link)


                'Dim q = DB.TAB.Account.
                '    REL.Account.Account_Link.
                '    REL.Account.Account_Add_Info.
                '    REL.Account.Account_Update

                'If f.IdsLink.Count <> 0 Then
                '    Dim links = f.IdsLink.Select(Function(o) DirectCast(o, mDB._Account_Link.Type)).ToList
                '    q.BY._Account_Link.Account_Id(Me.Id, links)
                'Else
                '    q.BY._Account_Link.Account_Id(Me.Id)
                'End If
                '_Account_Link.Type.FOLLOWER
                Dim linktype = _Account_Link.Type.FOLLOWER

                If f.IdsLink.Count > 0 Then
                    linktype = f.IdsLink(0)
                End If

                Dim q = Me._Tab_Account_Link(linktype).
                    REL._Account_Link.Account.
                    REL.Account.Account_Add_Info


                If f.IdsCat.Count <> 0 Or f.IdsCatNot.Count <> 0 Then
                    q.REL.Account.Categorize_Account()
                    If f.IdsCat.Count <> 0 Then
                        q.BY.Categorize_Account.Account_Id(Me.Id, f.IdsCat)
                    End If
                    If f.IdsCatNot.Count <> 0 Then
                        q.
                            BY.Categorize_Account.Account_Id(Me.Id).
                            Where("Categorize_Account.categorize_id", "not IN", f.IdsCatNot)
                    End If
                End If

                If f.IdsLang.Count <> 0 Then
                    q.Where("lang", "IN", f.IdsLang)
                End If

                If f.IdsLangNot.Count <> 0 Then
                    q.Where("lang", "not IN", f.IdsLangNot)
                End If

                If f.IdsGend.Count <> 0 Then
                    q.Where("gender_type_id", "IN", f.IdsGend)
                End If

                If f.IdsBusin.Count <> 0 Then
                    q.Where("business_type_id", "IN", f.IdsBusin)
                End If

                If f.IdsStatus.Count <> 0 Then
                    q.Where("status_type_id", "IN", f.IdsStatus)
                End If

                If f.FromDate > Date.MinValue Then
                    q.Where("create_date", ">=", f.FromDate)
                End If

                If f.ToDate() > Date.MinValue Then
                    q.Where("create_date", "<", f.ToDate.AddDays(1))
                End If

                If f.Username <> "" Then
                    q.Where("username", "like", SF("%{0}%", f.Username))
                End If

                If f.Fullname <> "" Then
                    q.Where("fullname", "like", SF("%{0}%", f.Fullname))
                End If

                If f.Verified <> 0 Then
                    q.Where("Verified", "=", f.Verified = 1)
                End If

                Return q

            End Function
            Public Class Filter
                Property FromDate As Date
                Property ToDate As Date
                Property Username As String
                Property Fullname As String
                Property IdsLink As New List(Of Integer)
                Property IdsCat As New List(Of Integer)
                Property IdsCatNot As New List(Of Integer)
                Property IdsLang As New List(Of String)
                Property IdsLangNot As New List(Of String)
                Property IdsGend As New List(Of Integer)
                Property IdsBusin As New List(Of Integer)
                Property IdsStatus As New List(Of Integer)
                Property Verified As Integer

            End Class

#End Region




        End Class

        Partial Public Class Account_Add_Info

            Private _Post_Hours As Integer()
            Public Property Post_Hours() As Integer()
                Get
                    If _Post_Hours Is Nothing Then
                        _Post_Hours = mDB.Account.GetActivityHours(Me.Post_Hours_Json)
                        'Dim i(23) As Integer
                        '_Post_Hours = MyApp.JSONDeserialize(Of Integer())(Me.Post_Hours_Json, i)
                    End If
                    Return _Post_Hours
                End Get
                Set(value As Integer())
                    Me._Post_Hours = MyApp.GetSetDataJson(value, Me.Post_Hours_Json)
                End Set
            End Property

            Private _Post_Weeks As Dictionary(Of String, Integer)
            Public Property Post_Weeks() As Dictionary(Of String, Integer)
                Get
                    If _Post_Weeks Is Nothing Then
                        _Post_Weeks = MyApp.JSONDeserializeObj(Of Dictionary(Of String, Integer))(Me.Post_Weeks_Json) '  mDB.Account.GetActivityHours(Me.Post_Weeks_Json)
                    End If
                    Return _Post_Weeks
                End Get
                Set(value As Dictionary(Of String, Integer))
                    Me._Post_Weeks = MyApp.GetSetDataJson(value, Me.Post_Weeks_Json)
                End Set
            End Property
        End Class

        Partial Public Class Account_Option

            'Public Property AutoFollNumber() As Integer
            '    Get
            '        Return newPropertyValue
            '    End Get
            '    Set(ByVal value As Integer)
            '        newPropertyValue = value
            '    End Set
            'End Property


        End Class

        Partial Public Class _Account_Link

            Public Enum Type
                FOLLOWER = 1
                FRIENDS = 2
                FOLLOWER_OLD = 3
                FRIEND_OLD = 4
                'TO_POST_SHARE = 3
            End Enum

            Public ReadOnly Property LinkType As Type
                Get
                    Return Me.Link_Type_Id
                End Get
            End Property

            Public Shared Function GetOldLinkType(LinkType As _Account_Link.Type) As _Account_Link.Type

                Select Case LinkType
                    Case Type.FOLLOWER
                        Return Type.FOLLOWER_OLD
                    Case Type.FRIENDS
                        Return Type.FRIEND_OLD
                    Case Type.FOLLOWER_OLD
                        Return Type.FOLLOWER
                    Case Type.FRIEND_OLD
                        Return Type.FRIENDS
                    Case Else
                        Return Nothing
                End Select


            End Function

        End Class

        Partial Public Class Archive_Data
            Public Enum Type
                ACCOUNT_POST = 1
                QUERY_POST = 2
                QUERY_ACCOUNT = 3
                ACCOUNT_TREND = 4
                ACCOUNT_LINK = 5

            End Enum

            'Public Shared Function GetUpdateArchine(DB As mDB, t As Type, ByRef ArchiveId As Integer) As Archive_Data

            '    Dim Archive As Archive_Data
            '    If ArchiveId = 0 Then
            '        Archive = DB.TAB.Archive_Data.BY.Archive_Data.Archive_Type_Id(t).OrderBy("Record_Count").ToObj
            '        Archive.Record_Count += 1
            '        ArchiveId = Archive.Id
            '    Else
            '        Archive = DB.TAB.Archive_Data.GetByPK(ArchiveId)
            '    End If

            '    Return Archive

            'End Function

            Public Shared Function GetUpdateArchine(db As mDB, entity As Object, t As Type, ByRef ArchiveFiled As String) As Archive_Data
                Dim ArchiveId As Integer = db.GetFieldValue(entity, ArchiveFiled)


                Dim Archive As Archive_Data
                If ArchiveId = 0 Then
                    Archive = db.TAB.Archive_Data.BY.Archive_Data.Archive_Type_Id(t).OrderBy("Record_Count").ToObj
                    Archive.Record_Count += 1
                    db.SetFieldValue(entity, ArchiveFiled, Archive.Id)
                    'ArchiveId = Archive.Id
                    db.SubmitChanges()
                Else
                    Archive = db.TAB.Archive_Data.GetByPK(ArchiveId)
                End If

                Return Archive

            End Function


        End Class
        Partial Public Class Archive_Simil_Text


            Public Function GetSimilTextArchiveData() As SimilText.ArchiveData

                'Dim archiveid = GetArchive(Me.ArchiveTypeId, Me.RefId).ArchiveId
                Dim AD = SimilText.ArchiveData.GetData(Me.Archive_Id)

                Return AD

            End Function
            Public Sub RemoveSimilTextArchiveData()

                'Dim archiveid = GetArchive(1, CurrAccount.Id).ArchiveId
                SimilText.ArchiveData.RemoveData(Me.Archive_Id)

            End Sub

            'questo si può associare all'archive_simil_text
            Public Enum ArchiveType
                POST_FOLLOWERS = 1
                POST_QUERY = 2
                POST_ACCOUNT = 3

            End Enum


            Public Shared Function GetArchive(archiveType As ArchiveType, RedID As Integer) As mDB.Archive_Simil_Text
                Dim DB = mDB.GetDB '(False) ' 'questo perchè viene utilizzata anche in async

                Dim archive = DB.TAB.Archive_Simil_Text.
                    Where("archive_type_id", "=", archiveType).
                    Where("ref_id", "=", RedID).
                ToObj

                If archive Is Nothing Then

                    archive = New mDB.Archive_Simil_Text With {.Archive_Type_Id = archiveType, .Ref_Id = RedID}
                    DB.TAB.Archive_Simil_Text.InsertOnSubmit(archive)
                    DB.SubmitChanges()

                End If

                Return archive

            End Function


        End Class

        Partial Public Class Categorize
            Implements UI.Validator.Ivalidator

            Public Enum Type
                TEMP = 0
            End Enum

            Public Function SubmitChanges() As Boolean
                Dim db = mDB.GetDB

                If Me.Validate.Count = 0 Then
                    db.SubmitChanges()
                    Return True
                Else
                    db.ResetChanges()
                    Return False
                End If

            End Function

            'Public Function SubmitChanges() As Boolean
            '    Dim db = mDB.GetDB
            '    Dim Val As New Validator With {.ObjToValidate = Me}

            '    If Val.ValidatorCheck.Count = 0 Then
            '        db.SubmitChanges()
            '        Return True
            '    Else
            '        db.ResetChanges()
            '        Return False
            '    End If


            'End Function

            'Public Class Validator
            '    Inherits UI.Validator.ValidatorBase(Of Categorize)


            '    Protected Overrides Function CheckValidation() As UI.Validator.ValidatorResult

            '        Dim db = mDB.GetDB
            '        Dim res As UI.Validator.ValidatorResult
            '        Dim fold = db.TAB.Folder.GetByPK(Me.ObjToValidate.Folder_Id)
            '        Dim acc = db.TAB.Categorize.REL.Categorize.Folder.BY.Folder.User_Id(fold.User_Id).
            '            Where("categorize.id", "<>", Me.ObjToValidate.Id).
            '            WhereOp("and", "or", "description", "=", Me.ObjToValidate.Description, "Query", "=", Me.ObjToValidate.Query).
            '        ToList

            '        If acc.Count > 0 Then
            '            Return (New UI.Validator.ValidatorResult).Add("") ' From      'StyleUriParser Me.ValidatorObj.Add("DUP")
            '        End If



            '    End Function
            'End Class

            'Public Class Validator
            '    Inherits UI.Validator.ValidatorBase(Of Categorize)


            '    Protected Overrides Function CheckValidation() As UI.Validator.ValidatorResult


            '        Return Me.ObjToValidate.Validate



            '    End Function
            'End Class

            Public Function Validate() As UI.Validator.ValidatorResult Implements UI.Validator.Ivalidator.Validate

                Dim db = mDB.GetDB
                Dim res As New UI.Validator.ValidatorResult
                Dim fold = db.TAB.Folder.GetByPK(Me.Folder_Id)
                Dim acc = db.TAB.Categorize.REL.Categorize.Folder.BY.Folder.User_Id(fold.User_Id).
                    Where("categorize.id", "<>", Me.Id).
                    WhereOp("and", "or", "description", "=", Me.Description, "Query", "=", Me.Query).
                ToList

                If acc.Count > 0 Then
                    res.Add("DUP")
                End If

                Return res

            End Function
        End Class

        'Partial Public Class Filter_Account

        '    Public Property Filter() As FilterAccount
        '        Get
        '            Return MyApp.JSONDeserializeObj(Of FilterAccount)(Me.Params)
        '        End Get
        '        Set(ByVal value As FilterAccount)
        '            Me.Params = MyApp.JSONSerialize(value)
        '        End Set
        '    End Property

        '    Public Class FilterAccount
        '        Property FromDate As Date
        '        Property ToDate As Date
        '        Property Username As String
        '        Property Fullname As String
        '        Property IdsLink As List(Of Integer)
        '        Property IdsCat As List(Of Integer)
        '        Property IdsLang As List(Of String)
        '        Property IdsLangNot As List(Of String)
        '        Property IdsGend As List(Of Integer)
        '        Property IdsBusin As List(Of Integer)
        '    End Class
        'End Class
        'Partial Public Class Data_Json

        '    Public Function GetObj(Of tres As {New})() As tres
        '        Return MyApp.JSONDeserializeObj(Of tres)(Me.Json)
        '    End Function

        '    Public Function GetObj() As Object
        '        Return MyApp.JSONDeserialize(Me.Json)
        '    End Function

        '    Public Sub SetObj(o As Object)
        '        Me.Json = MyApp.JSONSerialize(o)
        '    End Sub

        '    Public Shared Sub SaveObj(db As mDB, ByRef data_id As Integer, o As Object)
        '        Dim S = db.TAB.Data_Json.GetByPK(data_id)

        '        If S Is Nothing Then
        '            S = New Data_Json
        '            db.TAB.Data_Json.InsertOnSubmit(S)
        '            db.SubmitChanges()
        '            data_id = S.Id
        '        End If

        '        S.SetObj(o)

        '    End Sub

        '    Public Property FilterAccount() As Account.Filter
        '        Get
        '            Return Me.GetObj(Of Account.Filter)()
        '        End Get
        '        Set(ByVal value As Account.Filter)
        '            Me.SetObj(value)
        '        End Set
        '    End Property


        'End Class

        Partial Class Favorite_Post

            Public Shared Function GetForUpdate(AccountId As Integer, PostCode As String) As Favorite_Post
                Dim db = mDB.GetDB

                Dim Favorite = db.TAB.Favorite_Post.BY.Favorite_Post.Account_Id(AccountId, PostCode).ToObj

                If Favorite Is Nothing Then
                    Favorite = New mDB.Favorite_Post

                    Favorite.Account_Id = AccountId
                    Favorite.Post_Code = PostCode

                    db.TAB.Favorite_Post.InsertOnSubmit(Favorite)

                End If

                Return Favorite

            End Function

        End Class

        Partial Class List

            Public Enum Type
                [PRIVATE] = 1
                [PUBLIC] = 2
                [LOCAL] = 3
            End Enum

            Public ReadOnly Property Tab_List_Account() As BuildQuery(Of List_Account)
                Get
                    Return DB.TAB.List_Account.BY.List_Account.List_Id(Me.Id)
                End Get
            End Property


            Private _Account As Account
            Public ReadOnly Property Account() As Account
                Get
                    If _Account Is Nothing Then
                        _Account = DB.TAB.Account.GetByPK(Me.Account_Id)
                    End If
                    Return _Account
                End Get
            End Property


        End Class


        Partial Public Class Folder

            Public Enum DataType
                QUERY = 1
                CATEGORIZE = 2
                PROFILE = 3

                'PRIVATE_MESSAGE = 3
            End Enum
            Public Enum Type
                TWITTER_QUERY = 1
                TWITTER_CATEGORIZE = 2

                FACEBOOK_QUERY = 200
                FACEBOOK_CATEGORIZE = 201

                GOOGLE_QUERY = 300
                GOOGLE_CATEGORIZE = 301

                'PRIVATE_MESSAGE = 3
            End Enum

            Private _User As mDB.User
            Public ReadOnly Property User() As User
                Get
                    If _User Is Nothing Then
                        _User = DB.TAB.User.GetByPK(Me.User_Id)
                    End If
                    Return _User
                End Get
            End Property


            Public Shared Function GetFolderType(f As DataType, n As MyApp.Network.AccType) As Type

                Dim t As Type = -1
                Select Case f
                    Case DataType.QUERY
                        Select Case MyApp.Network.AccTypeToNetType(n)
                            Case WebApi.Type.TWITTER
                                t = Type.TWITTER_QUERY
                            Case WebApi.Type.FACEBOOK
                                t = Type.FACEBOOK_QUERY
                            Case WebApi.Type.GOOGLE
                                t = Type.GOOGLE_QUERY
                        End Select
                    Case DataType.CATEGORIZE
                        Select Case MyApp.Network.AccTypeToNetType(n)
                            Case WebApi.Type.TWITTER
                                t = Type.TWITTER_CATEGORIZE
                            Case WebApi.Type.FACEBOOK
                                t = Type.FACEBOOK_CATEGORIZE
                            Case WebApi.Type.GOOGLE
                                t = Type.GOOGLE_CATEGORIZE
                        End Select
                End Select

                Return t

            End Function
            Public Shared Function GetDataType(t As Type) As DataType

                Dim f As DataType = -1
                Select Case t
                    Case Type.TWITTER_QUERY, Type.FACEBOOK_QUERY
                        f = DataType.QUERY
                    Case Type.TWITTER_CATEGORIZE, Type.FACEBOOK_CATEGORIZE
                        f = DataType.CATEGORIZE
                End Select

                Return f

            End Function



            Public Sub InsertOnSubmit(DB As mDB)

                DB.TAB.Folder.InsertOnSubmit(Me)
                'DB.AddChangedHandle(Me)
                DB.TAB.Folder.AddChangedHandle(Me)
            End Sub

            Private Sub OnIdChanged()

                If Me.DB IsNot Nothing Then
                    Me.Ref_Id = Me.Id
                End If

            End Sub
        End Class

        Partial Public Class Follower_Analysis

            Public Enum Type
                GENDER = 1
                PLACE = 2
                HOURS_ACTIVITY = 3
                LANGUAGE = 4
                BUSINESS = 5
                STATUS = 6
                FOLLOWERS_COUNT = 7
            End Enum


        End Class

        Partial Public Class Auto_Follow_Account
            Public Enum StatusType
                PENDING = 1             ' inserito nella tabella
                FOLLOW = 2           ' effettualo il follow
                ALREADY_FRIEND = 3   ' è stato riscontrato che l'utente erà gia seguito
                BECOME_FOLLOWER = 4     ' l'utente è diventato a sua volta un follower
                UNFOLLOW = 5            ' è stato fatto un unfollow perchè dopo un tot di tempo non è diventato un follower
                [ERROR] = 99
            End Enum

            Public Enum SourceType
                QUERY = 1
                PROFILE_FOLLOWER = 2
                UNFOLL_NO_FOLLOWER = 3
            End Enum

            Private _Account As Account
            Public ReadOnly Property Account_To_Foll() As Account
                Get
                    If _Account Is Nothing Then
                        _Account = DB.TAB.Account.GetByPK(Me.Account_To_Foll_Id)
                    End If
                    Return _Account
                End Get
            End Property

            'ElmBySourceId
            Class FillList
                Property ResultList As New List(Of mDB.Auto_Follow_Account)
                Property InputList As List(Of mDB.Auto_Follow_Account)
                Property Types As New Dictionary(Of mDB.Auto_Follow_Account.SourceType, Integer)

                Private SourceType As New Dictionary(Of Integer, mDB.Auto_Follow_Account.GetByType)
                'Property FollAccAll As List(Of mDB.Auto_Follow_Account)
                Private MaxResult As Integer

                Public Function FillList() As List(Of mDB.Auto_Follow_Account)

                    MaxResult = 0
                    For Each id In Types
                        SourceType.Add(id.Key, New mDB.Auto_Follow_Account.GetByType(InputList.Where(Function(o) o.Source_Type_Id = id.Key).ToList, id.Value))
                        MaxResult += id.Value
                    Next

                    AddList()

                    For Each id In SourceType
                        If SourceType(id.Key).FollAccs.Count > 0 Then
                            SourceType(id.Key).MaxToGive = Integer.MaxValue
                        End If

                    Next

                    AddList()

                    Return ResultList

                End Function
                Private Sub AddList()

                    Dim Add = True
                    Do Until ResultList.Count >= MaxResult Or Add = False
                        Add = False
                        For Each id In SourceType
                            Dim o = SourceType(id.Key).GetNext
                            If o IsNot Nothing Then
                                ResultList.Add(o)
                                Add = True
                            End If
                        Next
                    Loop
                End Sub

            End Class

            Class GetByType
                Property FollAccs As List(Of mDB.Auto_Follow_Account)
                Property MaxToGive As Integer
                Property GiveCount As Integer

                Private CurrPos As Integer
                Private Group As New Dictionary(Of Integer, Integer)

                Sub New(TypeAcc As List(Of mDB.Auto_Follow_Account), g As Integer)
                    Me.MaxToGive = g
                    FollAccs = TypeAcc
                    Dim TypeIds = FollAccs.Select(Function(o) o.Source_Id).Distinct.ToList()
                    For Each id In TypeIds
                        Group.Add(id, 0)
                    Next
                    CurrPos = 0
                    GiveCount = 0

                End Sub
                Public Function GetNext() As mDB.Auto_Follow_Account
                    Dim o As mDB.Auto_Follow_Account = Nothing

                    If GiveCount < MaxToGive Then

                        Do Until FollAccs.Count = 0 Or o IsNot Nothing
                            Dim otmp = FollAccs(CurrPos)

                            If Group(otmp.Source_Id) = 0 Then
                                Group(otmp.Source_Id) = 1
                                FollAccs.Remove(otmp)
                                o = otmp
                                GiveCount += 1
                            End If

                            CurrPos += 1
                            If CurrPos > FollAccs.Count - 1 Then
                                CurrPos = 0

                                Dim k = Group.Select(Function(oo) oo.Key).ToList
                                For Each sss In k
                                    Group(sss) = 0
                                Next

                            End If

                        Loop

                    End If


                    Return o

                End Function

            End Class
        End Class

        Partial Public Class Media

            Private Function CreatePath() As String

                Dim IndexesPath = ""
                ' crea path dell indice
                Dim IdStr = Me.Id.ToString
                If IdStr.Length Mod 2 = 1 Then
                    IdStr = "0" & IdStr
                End If

                For ct = 0 To (IdStr.Length) / 2 - 1
                    IndexesPath &= IdStr.Substring(ct * 2, 2) & "\"
                Next

                Return IndexesPath

            End Function

            Private Function PathBase() As String

                Return New IO.DirectoryInfo(HttpContext.Current.Server.MapPath("~/")).Parent.FullName & "\media\" '     IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/")).Parent.FullName

            End Function
            Public Function FullPathMedia() As String

                Return PathBase() & Me.App_Url

            End Function
            Public Function PublicUrl() As String
                Return "http://" & HttpContext.Current.Request.Url.Host & "/app/MediaUpload.aspx?id=" & Me.Id
            End Function


            Public Sub AttachMedia(f As String, ss As IO.Stream)


                Dim RootPath = PathBase() '     IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/")).Parent.FullName
                'IO.DirectoryInfo()
                Dim FilePath = CreatePath()
                If Not IO.Directory.Exists(RootPath & FilePath) Then
                    IO.Directory.CreateDirectory(RootPath & FilePath)
                End If


                Dim ext = IO.Path.GetExtension(f)
                Dim fileName As String = IO.Path.GetRandomFileName.Replace(".", "") & ext '  Context.Request.QueryString("")
                Dim fullFileName As String = RootPath & FilePath & fileName  '  Context.Request.QueryString("")

                Dim file = IO.File.Create(fullFileName)

                Dim fileBytes(ss.Length - 1) As Byte '() = New Byte() {}
                ss.Read(fileBytes, 0, fileBytes.Length)

                file.Write(fileBytes, 0, fileBytes.Length)
                file.Close()

                Me.Create_Date = Date.UtcNow
                Me.App_Url = FilePath & fileName
                Me.Client_File_Name = f
                DB.SubmitChanges()



            End Sub

            Public Sub cancella()

            End Sub

            Public Function ToBase64() As String

                Dim s = Me.ToStream
                Dim buff(s.Length - 1) As Byte
                s.Read(buff, 0, s.Length)
                Dim img = Convert.ToBase64String(buff)
                s.Close()

                Return img
            End Function

            Public Function ToStream() As IO.Stream

                Dim f = IO.File.OpenRead(FullPathMedia)
                Return f

            End Function

        End Class



        Partial Public Class Gender_Name

            Public Enum Type
                UNKNOW = -1
                NOT_ASSIGNED = 0
                MALE = 1
                FEMALE = 2
                UNISEX = 3
            End Enum

        End Class

        Partial Public Class Profile
            Public Enum UpdateStatusType
                NONE
                QUEUED
            End Enum
            Public Enum DataStausType
                OK
                EMPTY
            End Enum

            Public ReadOnly Property UpdateStatus() As UpdateStatusType
                Get
                    If Me.Post_Download_Count < 0 Then
                        Return UpdateStatusType.QUEUED
                    Else
                        Return UpdateStatusType.NONE
                    End If

                End Get
            End Property
            Public ReadOnly Property DataStatus() As DataStausType
                Get
                    If Me.Post_Count = 0 Then
                        Return DataStausType.EMPTY
                    Else
                        Return DataStausType.OK
                    End If
                End Get
            End Property

            Private _Account As Account
            Public ReadOnly Property Account() As Account
                Get
                    If _Account Is Nothing Then
                        _Account = DB.TAB.Account.GetByPK(Me.Account_Id)
                    End If
                    Return _Account
                End Get
            End Property

            Public Sub ReIndex()

                'Me.Post_Count = 0
                Me.Post_Download_Count = -1
                'Me.Last_Update_Date = Date.MinValue

            End Sub

        End Class

        Partial Public Class _Query_Post

            'Public Shared Function GetLastPostFromQueries(qs As List(Of mDB.Query), Max As Integer) As List(Of mDB._Query_Post)

            '    Dim Posts As New List(Of mDB._Query_Post)
            '    Dim Lastdate As Date = Date.MinValue

            '    For Each q In qs

            '        Posts.AddRange(q._Tab_Query_Post.OrderBy("pubb_date desc").Limit(Max).ToList)
            '        Posts = (From p In Posts Order By p.Pubb_Date Descending Take Max).ToList

            '    Next

            '    Return Posts

            'End Function
            Public Shared Function FillPost(posts As List(Of mDB._Query_Post), queries As List(Of mDB.Query)) As List(Of mDB._Query_Post)

                Dim QueryPostIds As New Dictionary(Of Integer, List(Of Integer))
                Dim querydic = queries.ToDictionary(Of Integer)(Function(o) o.Id)

                For Each p In posts
                    If Not QueryPostIds.ContainsKey(p.Query_Id) Then
                        QueryPostIds.Add(p.Query_Id, New List(Of Integer))
                    End If

                    QueryPostIds(p.Query_Id).Add(p.Id)

                Next

                Dim RetPosts As New List(Of mDB._Query_Post)

                For Each q In QueryPostIds

                    RetPosts.AddRange(querydic(q.Key)._Tab_Query_Post.Where("id", "IN", q.Value).ToList)

                Next

                Return RetPosts

            End Function

            'Public Shared Function GetPostFromQueryIds(ids As Dictionary(Of Integer, List(Of Integer)), qs As Dictionary(Of Integer, mDB.Query), Max As Integer) As List(Of mDB._Query_Post)

            '    Dim Posts As New List(Of mDB._Query_Post)

            '    For Each q In ids

            '        Dim query = qs(q.Key)

            '        Posts.AddRange(query._Tab_Query_Post.Where("id", "IN", q.Value).ToList)

            '    Next

            '    Return Posts

            'End Function
            'Public Shared Function GetPostFromQueryIds(ids As Dictionary(Of Integer, List(Of Integer)), Max As Integer) As List(Of mDB._Query_Post)
            '    Dim db = mDB.GetDB

            '    Return GetPostFromQueryIds(ids, db.TAB.Query.Where("id", "IN", ids.Select(Function(o) o.Key).ToList).ToDictionary(Of Integer)("id"), Max)

            'End Function


        End Class

        Partial Public Class _Query_Account

            Public Enum Type
                NONE
                QUEUED
            End Enum



        End Class


        Partial Public Class Query
            Implements IQueryAnalysis


            Public Enum UpdateStatusType
                NONE
                QUEUED
            End Enum
            Public Enum DataStausType
                OK
                EMPTY
            End Enum
            Public Enum UpdateModeType
                NORMAL
                REALTIME
            End Enum

            Public Overrides Function ToString() As String

                Return SF("'{0}' [{1}]", Me.Query, Me.Id)

            End Function


            Public ReadOnly Property UpdateStatus() As UpdateStatusType
                Get
                    If Me.Post_Download_Count < 0 Then
                        Return UpdateStatusType.QUEUED
                    Else
                        Return UpdateStatusType.NONE
                    End If

                End Get
            End Property
            Public ReadOnly Property DataStatus() As DataStausType
                Get
                    If Me.Post_Count = 0 Then
                        Return DataStausType.EMPTY
                    Else
                        Return DataStausType.OK
                    End If
                End Get
            End Property

            Public Sub ReIndex()

                'Me.Post_Count = 0
                Me.Post_Download_Count = -1
                'Me.Last_Update_Date = Date.MinValue

            End Sub
            Public Function SetDefault() As Query

                Me.Post_Count = 0
                Me.Post_Download_Count = -1
                Me.Last_Update = Date.MinValue

                Return Me

            End Function

            Public ReadOnly Property Tab_Listen_Query() As BuildQuery(Of Listen_Query)
                Get
                    Return DB.TAB.Listen_Query.BY.Listen_Query.Query_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property _Tab_Query_Account() As BuildQuery(Of _Query_Account)
                Get
                    Dim q = New BuildQuery(Of _Query_Account)(DB, Me.ArchiveAccount.Table_Name)

                    Return q.BY._Query_Account._Query_id(Me.Id)

                End Get
            End Property

            Public ReadOnly Property _Tab_Query_Post() As BuildQuery(Of _Query_Post)
                Get
                    Dim q = New BuildQuery(Of _Query_Post)(DB, Me.ArchivePost.Table_Name)

                    Return q.BY._Query_Post._Query_id(Me.Id)

                End Get
            End Property

            Public Function GetLastPost() As mDB._Query_Post

                Return Me._Tab_Query_Post.OrderBy("pubb_date desc").Limit(1).ToObj

            End Function

            Public Function GetLastPostCode() As String

                Dim LastPost = Me.GetLastPost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return LastPost.Post_Code
                Else
                    Return ""
                End If

            End Function
            Public Function GetLastPostDateUniversalTimeStamp() As String

                Dim LastPost = Me.GetLastPost

                'prendo il post + nuovo
                If LastPost IsNot Nothing Then
                    Return Utils.Conv.ToTimeStamp(LastPost.Pubb_Date.ToUniversalTime).ToString
                Else
                    Return ""
                End If

            End Function


            Private Sub OnQueryChanged()
                If Me.DB IsNot Nothing Then
                    Me.SetDefault()
                End If
            End Sub


            Private _Folder As mDB.Folder
            Public ReadOnly Property Folder As mDB.Folder
                Get
                    If _Folder Is Nothing Then
                        _Folder = DB.TAB.Folder.GetByPK(Me.Folder_Id)
                    End If
                    Return _Folder

                End Get
            End Property

            Private _ArchivePost As mDB.Archive_Data
            Public ReadOnly Property ArchivePost As mDB.Archive_Data
                Get
                    If _ArchivePost Is Nothing Then
                        _ArchivePost = Archive_Data.GetUpdateArchine(DB, Me, Archive_Data.Type.QUERY_POST, "Archive_Post_Id")
                    End If
                    Return _ArchivePost

                End Get
            End Property

            Private _ArchiveAccount As mDB.Archive_Data
            Public ReadOnly Property ArchiveAccount As mDB.Archive_Data
                Get
                    If _ArchiveAccount Is Nothing Then
                        _ArchiveAccount = Archive_Data.GetUpdateArchine(DB, Me, Archive_Data.Type.QUERY_ACCOUNT, "Archive_Account_Id")
                    End If
                    Return _ArchiveAccount

                End Get
            End Property


            Public Function GetTrendAccount(FromDate As Date, ToDate As Date) As List(Of mDB._Query_Account) Implements IQueryAnalysis.GetTrendAccount

                Return Me._Tab_Query_Account.
                    Where("post_update", ">=", FromDate, "post_update", "<=", ToDate).
                    GroupBy("post_update").
                    SetSelect("post_update", "sum(post_count) as post_count", "sum(account_follower_count * post_count) as account_follower_count").
                ToList()

            End Function

            Public Function View_Account_Search(FromDate As Date, ToDate As Date, Username As String) As BuildQuery(Of mDB._Query_Account)

                Dim qSingleQuery = Me._Tab_Query_Account

                If FromDate > Date.MinValue Then
                    qSingleQuery.Where("post_update", ">=", FromDate)
                End If

                If ToDate > Date.MinValue Then
                    qSingleQuery.Where("post_update", "<", ToDate.AddDays(1))
                End If


                If Username <> "" Then
                    qSingleQuery.Where("account_username", "like", SF("%{0}%", Username))
                End If


                Return qSingleQuery

            End Function

        End Class

        Partial Public Class Share_Post

            Public Shared Function GetForUpdate(PostCode As String) As Share_Post
                Dim db = mDB.GetDB

                Dim Share = db.TAB.Share_Post.BY.Share_Post.Post_Code(PostCode).ToObj

                If Share Is Nothing Then
                    Share = New mDB.Share_Post
                    Share.Share_Det_Count = 0
                    Share.Post_Code = PostCode
                    db.InsertOnSubmit(Share)

                End If

                Return Share

            End Function


            Public ReadOnly Property Tab_Share_Detail() As BuildQuery(Of Share_Detail)
                Get
                    Return DB.TAB.Share_Detail.BY.Share_Detail.Share_Post_Id(Me.Id)
                End Get
            End Property

        End Class



        Partial Public Class Task_Post
            Public Enum Type
                NORMAL = 0
                [PRIVATE] = 1
                SHARE = 2
            End Enum

            Private _Media As Media
            Public Property Media() As Media
                Get
                    If _Media Is Nothing Then
                        _Media = DB.TAB.Media.GetByPK(Me.Media_Id)
                    End If
                    Return _Media
                End Get
                Set(value As Media)
                    _Media = value
                    If Me.DB Is Nothing Then
                        Me.Media_Id = -1
                    End If

                End Set
            End Property

        End Class
        Partial Class Task_Scheduler

            Public Function SetDefault() As Task_Scheduler

                Me.Begin_Date = Date.UtcNow
                Me.Repeat_To_Time = "23:59"
                Me.Repeat_Every_Time = "00:30"
                Me.End_Date = Date.UtcNow.Date.AddDays(7)

                Me.Repeat_Day_Week = GetRepeatDayDefault()

                Return Me

            End Function

            Private _Repeat_Day_Week As Dictionary(Of String, Integer)
            Public Property Repeat_Day_Week() As Dictionary(Of String, Integer)
                Get
                    If _Repeat_Day_Week Is Nothing Then
                        _Repeat_Day_Week = MyApp.JSONDeserializeObj(Of Dictionary(Of String, Integer))(Me.Repeat_Day_Week_Json) '  mDB.Account.GetActivityHours(Me.Post_Weeks_Json)
                    End If
                    If _Repeat_Day_Week.Count <> 7 Then
                        _Repeat_Day_Week = GetRepeatDayDefault()
                    End If
                    Return _Repeat_Day_Week
                End Get
                Set(value As Dictionary(Of String, Integer))
                    Me._Repeat_Day_Week = MyApp.GetSetDataJson(value, Me.Repeat_Day_Week_Json)
                End Set
            End Property

            Public Function GetRepeatDayDefault() As Dictionary(Of String, Integer)

                Dim d As New Dictionary(Of String, Integer)
                For ct = 0 To 6
                    d.Add(ct, 1)
                Next

                Return d
            End Function
        End Class



        Partial Public Class Task_Send

            Private _TaskSchedulerList As List(Of Task_Scheduler)
            Public ReadOnly Property TaskSchedulerList() As List(Of Task_Scheduler)
                Get
                    If _TaskSchedulerList Is Nothing Then
                        _TaskSchedulerList = Me.Tab_Task_Scheduler.ToList
                    End If
                    Return _TaskSchedulerList
                End Get
            End Property

            Private _Next_Send_Task_Scheduler As Task_Scheduler
            Public ReadOnly Property Next_Send_Task_Scheduler() As Task_Scheduler
                Get
                    If _Next_Send_Task_Scheduler Is Nothing Then
                        _Next_Send_Task_Scheduler = DB.TAB.Task_Scheduler.GetByPK(Me.Next_Send_Task_Scheduler_Id)
                    End If
                    Return _Next_Send_Task_Scheduler
                End Get
            End Property

            Private _Share_Account As Account
            Public ReadOnly Property Share_Account() As Account
                Get
                    If _Share_Account Is Nothing Then
                        _Share_Account = DB.TAB.Account.GetByPK(Me.Share_Account_Id)
                    End If
                    Return _Share_Account
                End Get
            End Property

            Private _Auto_Post_Filter As Account.Filter
            Public Property Auto_Post_Filter() As Account.Filter
                Get
                    If _Auto_Post_Filter Is Nothing Then
                        _Auto_Post_Filter = MyApp.JSONDeserializeObj(Of Account.Filter)(Me.Auto_Post_Filter_Json)
                    End If
                    Return _Auto_Post_Filter
                End Get
                Set(value As Account.Filter)
                    Me._Auto_Post_Filter = MyApp.GetSetDataJson(value, Me.Auto_Post_Filter_Json)
                End Set
            End Property

            Private _Auto_Post_Text_List As List(Of String)
            Public Property Auto_Post_Text_List() As List(Of String)
                Get
                    If _Auto_Post_Text_List Is Nothing Then
                        _Auto_Post_Text_List = MyApp.JSONDeserializeObj(Of List(Of String))(Me.Auto_Post_Text)
                    End If
                    Return _Auto_Post_Text_List
                End Get
                Set(value As List(Of String))
                    Me._Auto_Post_Text_List = MyApp.GetSetDataJson(value, Me.Auto_Post_Text)
                End Set
            End Property


            Public Function SetDefault() As Task_Send
                Me.Enabled_Task = 1

                Return Me

            End Function

            'Private _Auto_Post_Filter_Data As Account.Filter
            'Public Property Auto_Post_Filter_Data() As Account.Filter
            '    Get
            '        If _Auto_Post_Filter_Data Is Nothing Then
            '            Dim S = DB.TAB.Data_Json.GetByPK(Me.Auto_Post_Filter_Data_Id) '   User_Session.GetByPK(Me.Id)
            '            If S IsNot Nothing Then
            '                _Auto_Post_Filter_Data = S.GetObj(Of Account.Filter)()  '   MyApp.JSONDeserialize(TmpSess)
            '            End If
            '        End If
            '        Return _Auto_Post_Filter_Data
            '    End Get
            '    Set(ByVal value As Account.Filter)

            '        Me._Auto_Post_Filter_Data = value

            '    End Set
            'End Property

            'Public Sub SaveAuto_Post_Filter_Data()

            '    Data_Json.SaveObj(DB, Me.Auto_Post_Filter_Data_Id, Me.Auto_Post_Filter_Data)
            '    DB.SubmitChanges()

            'End Sub

            Private _Account As Account
            Public ReadOnly Property Account() As Account
                Get
                    If _Account Is Nothing Then
                        _Account = DB.TAB.Account.GetByPK(Me.Account_Id)
                    End If
                    Return _Account
                End Get
            End Property


            Public Function CheckSendPostDayLimit() As Boolean


                If Me.Post_Send_Count >= Me.Send_Max_Day And Me.Send_Max_Day > 0 And Me.Last_Send_Date.Date = Date.UtcNow.Date Then
                    Return True
                Else
                    Return False
                End If

            End Function
            Public Sub SetNextSend() 'As Date

                Dim MinDate = Date.MaxValue
                Dim TaskShecId = 0
                Dim DateRef = Me.Account.LDate(Date.UtcNow)

                Me.Expired_Task = False

                'se sono stati inviati tutti i post possibioli di oggi la data di riferimento per il prossimo invio parte da domani
                If Me.CheckSendPostDayLimit Then
                    DateRef = Me.Account.LDate(Date.UtcNow).Date.AddDays(1)
                End If

                For Each t In Me.TaskSchedulerList

                    '-----------------------------------------
                    'imposta la data da cui partire
                    '-----------------------------------------
                    Dim TaskDate = Me.Account.LDate(t.Begin_Date)

                    If t.Repeat_Day Then
                        If Me.Account.LDate(t.Begin_Date) < DateRef And Me.Account.LDate(t.End_Date) > DateRef Then
                            TaskDate = DateRef.Date.Add(Me.Account.LTime(t.Begin_Date.TimeOfDay))
                        End If
                    Else
                        'se non ci sono ripetizioni di giorno la data di fini è = alla data d'inizio
                        t.End_Date = t.Begin_Date
                    End If

                    '-----------------------------------------
                    'avanzio con il tempo nel giono
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue And (t.Range_Time) Then
                        Dim Timeto = Utils.Conv.ToTimeSpan(t.Repeat_To_Time)
                        Dim TimeEvery = Utils.Conv.ToTimeSpan(t.Repeat_Every_Time)

                        Do Until TaskDate > DateRef
                            TaskDate = TaskDate.Add(TimeEvery)
                            ' se sfora nella giornata
                            If TaskDate > TaskDate.Date.Add(Timeto) Then
                                If t.Repeat_Day Then
                                    'vado all'inizio del giono successivo
                                    TaskDate = TaskDate.Subtract(Timeto).Date.AddDays(1).Add(Me.Account.LTime(t.Begin_Date.TimeOfDay))
                                Else
                                    'se non posso andare nel giorno successivo il task è finito
                                    TaskDate = Date.MaxValue
                                End If
                            End If

                        Loop

                    End If

                    '-----------------------------------------
                    'avanzio nel giono giusto
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue And (t.Repeat_Day) Then

                        Do Until t.Repeat_Day_Week(TaskDate.DayOfWeek) = 1 And TaskDate > DateRef
                            TaskDate = TaskDate.Date.AddDays(1).Add(Me.Account.LTime(t.Begin_Date.TimeOfDay))
                        Loop

                    End If

                    '-----------------------------------------
                    'sporco un po' la data nel giono giusto
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue Then
                        Dim MinOffSet As Integer = 10
                        If t.Range_Time Then
                            Dim TimeEvery = Utils.Conv.ToTimeSpan(t.Repeat_Every_Time)
                            MinOffSet = Math.Min(MinOffSet, TimeEvery.TotalMinutes * 0.2D)
                        End If
                        TaskDate = TaskDate.AddMinutes((New Random()).Next(0, MinOffSet * 2 + 1))
                    End If


                    'IMPORTANTE se la data trovata è scaduta deve essere annullata
                    If TaskDate >= Me.Account.LDate(t.End_Date).AddDays(1) Then
                        TaskDate = Date.MaxValue
                    End If

                    'controlla se la data trovata è minore delle altre
                    If TaskDate < MinDate And TaskDate > DateRef Then
                        MinDate = TaskDate
                        TaskShecId = t.Id
                    End If

                Next

                'controlla se non è stata trovata nessuna data valida
                If MinDate = Date.MaxValue Then

                    Me.Close()
                    Me.Expired_Task = True

                Else

                    Me.Next_Send_Date = Me.Account.UtcDate(MinDate)
                    Me.Next_Send_Task_Scheduler_Id = TaskShecId

                    'verifica il post successivo
                    Dim p = Me.GetNextPost
                    'se non è stato trovato il post successivo e c'è la ripetizione dei post
                    If p Is Nothing And Me.Repeat_Send_Post Then
                        ' cerca il prossimo tra tutti
                        p = Me.GetFirstPost(False)
                    End If

                    Me.Next_Send_Post = ""
                    If p IsNot Nothing Then
                        Me.Next_Send_Post = SF("{0} {1} ""{2}""",
                            IIf(p.Post_Type_Id = mDB.Task_Post.Type.PRIVATE, "PRIVATE", ""),
                            IIf(p.To_Account_Username <> "", "@" & p.To_Account_Username, ""),
                            p.Post_Text
                        )
                    Else
                        'se non trova nulla il task è completo
                        Me.Close()
                    End If

                End If


            End Sub
            Public Sub SetNextSend_old() 'As Date

                Dim MinDate = Date.MaxValue
                Dim TaskShecId = 0
                Dim DateRef = Date.UtcNow

                Me.Expired_Task = False

                'se sono stati inviati tutti i post possibioli di oggi la data di riferimento per il prossimo invio parte da domani
                If Me.CheckSendPostDayLimit Then
                    DateRef = Date.UtcNow.Date.AddDays(1)
                End If

                For Each t In Me.TaskSchedulerList

                    '-----------------------------------------
                    'imposta la data da cui partire
                    '-----------------------------------------
                    Dim TaskDate = t.Begin_Date

                    If t.Repeat_Day Then
                        If t.Begin_Date < DateRef And t.End_Date > DateRef Then
                            TaskDate = DateRef.Date.Add(t.Begin_Date.TimeOfDay)
                        End If
                    Else
                        'se non ci sono ripetizioni di giorno la data di fini è = alla data d'inizio
                        t.End_Date = t.Begin_Date
                    End If

                    '-----------------------------------------
                    'avanzio con il tempo nel giono
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue And (t.Range_Time) Then
                        Dim Timeto = Utils.Conv.ToTimeSpan(t.Repeat_To_Time)
                        Dim TimeEvery = Utils.Conv.ToTimeSpan(t.Repeat_Every_Time)

                        Do Until TaskDate > DateRef
                            TaskDate = TaskDate.Add(TimeEvery)
                            ' se sfora nella giornata
                            If TaskDate > TaskDate.Date.Add(Timeto) Then
                                If t.Repeat_Day Then
                                    'vado all'inizio del giono successivo
                                    TaskDate = TaskDate.Subtract(Timeto).Date.AddDays(1).Add(t.Begin_Date.TimeOfDay)
                                Else
                                    'se non posso andare nel giorno successivo il task è finito
                                    TaskDate = Date.MaxValue
                                End If
                            End If

                        Loop

                    End If

                    '-----------------------------------------
                    'avanzio nel giono giusto
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue And (t.Repeat_Day) Then

                        Do Until t.Repeat_Day_Week(TaskDate.DayOfWeek) = 1 And TaskDate > DateRef
                            TaskDate = TaskDate.Date.AddDays(1).Add(t.Begin_Date.TimeOfDay)
                        Loop

                    End If

                    '-----------------------------------------
                    'sporco un po' la data nel giono giusto
                    '-----------------------------------------
                    If TaskDate <> Date.MaxValue Then
                        Dim MinOffSet As Integer = 10
                        If t.Range_Time Then
                            Dim TimeEvery = Utils.Conv.ToTimeSpan(t.Repeat_Every_Time)
                            MinOffSet = Math.Min(MinOffSet, TimeEvery.TotalMinutes * 0.2D)
                        End If
                        TaskDate = TaskDate.AddMinutes((New Random()).Next(0, MinOffSet * 2 + 1))
                    End If


                    'IMPORTANTE se la data trovata è scaduta deve essere annullata
                    If TaskDate >= t.End_Date.AddDays(1) Then
                        TaskDate = Date.MaxValue
                    End If

                    'controlla se la data trovata è minore delle altre
                    If TaskDate < MinDate And TaskDate > DateRef Then
                        MinDate = TaskDate
                        TaskShecId = t.Id
                    End If

                Next

                'controlla se non è stata trovata nessuna data valida
                If MinDate = Date.MaxValue Then

                    Me.Close()
                    Me.Expired_Task = True

                Else

                    Me.Next_Send_Date = MinDate
                    Me.Next_Send_Task_Scheduler_Id = TaskShecId

                    'verifica il post successivo
                    Dim p = Me.GetNextPost
                    'se non è stato trovato il post successivo e c'è la ripetizione dei post
                    If p Is Nothing And Me.Repeat_Send_Post Then
                        ' cerca il prossimo tra tutti
                        p = Me.GetFirstPost(False)
                    End If

                    Me.Next_Send_Post = ""
                    If p IsNot Nothing Then
                        Me.Next_Send_Post = SF("{0} {1} ""{2}""",
                            IIf(p.Post_Type_Id = mDB.Task_Post.Type.PRIVATE, "PRIVATE", ""),
                            IIf(p.To_Account_Username <> "", "@" & p.To_Account_Username, ""),
                            p.Post_Text
                        )
                    Else
                        'se non trova nulla il task è completo
                        Me.Close()
                    End If

                End If


            End Sub

            Public Function GetFirstPost(OnlyNotSent As Boolean) As mDB.Task_Post

                Dim q = Me.Tab_Task_Post

                If OnlyNotSent Then
                    q.Where("send_post", "=", False)
                End If

                Return q.OrderBy("order_by").Limit(1).ToObj

            End Function
            Public Function GetLastPost(OnlyNotSent As Boolean) As mDB.Task_Post

                Dim q = Me.Tab_Task_Post

                If OnlyNotSent Then
                    q.Where("send_post", "=", False)
                End If

                Return q.OrderBy("order_by desc").Limit(1).ToObj

            End Function
            Public Function GetNextPost() As mDB.Task_Post

                Return Me.GetFirstPost(True)

            End Function
            Public Sub ReOrderPost(Randomize As Boolean)

                Dim q = Me.Tab_Task_Post

                If Randomize Then
                    q.OrderBy("RAND()")
                Else
                    q.OrderBy("order_by")
                End If

                Dim Posts = q.ToList

                Dim OrderBy As Integer = 0
                For Each P In Posts
                    OrderBy += 100
                    P.Order_By = OrderBy
                    DB.SubmitChanges()
                Next

            End Sub

            Public Enum MovePostType
                [NEXT] = 1
                PREV = 2
                BEGIN = 3
                [END] = 4
            End Enum

            Public Sub MovePost(Post As mDB.Task_Post, Move As MovePostType)

                Dim pos As Integer = Integer.MinValue
                Dim q = Me.Tab_Task_Post

                If Post.Order_By = 0 Then
                    Me.ReOrderPost(False)
                    Post = DB.TAB.Task_Post.GetByPK(Post.Id)
                End If

                Select Case Move
                    Case MovePostType.PREV
                        q.Where("order_by", "<", Post.Order_By).OrderBy("order_by desc").Limit(2)
                        If q.ToList.Count > 0 Then
                            pos = q.ToList.Sum(Function(o) o.Order_By) / 2
                        End If

                    Case MovePostType.NEXT
                        q.Where("order_by", ">", Post.Order_By).OrderBy("order_by").Limit(2)
                        If q.ToList.Count = 1 Then
                            pos = Post.Order_By + 200
                        ElseIf q.ToList.Count > 1 Then
                            pos = q.ToList.Sum(Function(o) o.Order_By) / 2

                        End If

                    Case MovePostType.BEGIN
                        q.OrderBy("order_by").Limit(1)
                        pos = q.ToObj.Order_By - 100

                    Case MovePostType.END
                        q.OrderBy("order_by desc").Limit(1)
                        pos = q.ToObj.Order_By + 100

                End Select

                If pos <> Integer.MinValue Then
                    Dim DiffPos = Math.Abs(Post.Order_By - pos)
                    Post.Order_By = pos

                    DB.SubmitChanges()

                    If DiffPos < 3 Or pos <= 0 Or pos > 1000000000 Then
                        Me.ReOrderPost(False)
                    End If
                End If

            End Sub


            Public Sub AddPost(Post As Task_Post)
                'Me.AddPosts(New List(Of Task_Post) From {Post})
                Post.Task_Send_Id = Me.Id
                DB.InsertOnSubmit(Post)
                DB.SubmitChanges()

            End Sub
            Public Function AddPost(Post As Task_Post, Account As Account) As Boolean

                Dim tpl As New MyApp.Task.TemplatePost With {.Account = Account}
                Post.Post_Text = tpl.Render(Post.Post_Text)

                If Not tpl.EmptyData Then
                    'Me.AddPosts(New List(Of Task_Post) From {Post})
                    Me.AddPost(Post)
                End If

                Return Not tpl.EmptyData

            End Function

            Public Sub AddPosts(Post As Task_Post, ToAccounts As List(Of Account), IsTpl As Boolean)

                Dim Posts As New List(Of Task_Post)

                For Each Acc In ToAccounts
                    Dim p = Post.Clone
                    p.To_Account_Username = Acc.Username

                    If IsTpl Then
                        Dim tpl As New MyApp.Task.TemplatePost With {.Account = Acc}
                        p.Post_Text = tpl.Render(p.Post_Text)
                    End If

                    Posts.Add(p)
                Next

                Me.AddPosts(Posts)

                'Me.AddPosts(Post, ToAccounts.Select(Function(o) o.Username).ToList)

            End Sub
            Public Sub AddPosts(Post As Task_Post, ToUserAccounts As List(Of String))

                Dim ToAcc = (From u In ToUserAccounts Select New mDB.Account With {.Username = u}).ToList

                Me.AddPosts(Post, ToAcc, False)

                'Dim Posts As New List(Of Task_Post)

                'For Each User In ToUserAccounts
                '    Dim p = Post.Clone
                '    p.To_Account_Username = User
                '    Posts.Add(p)
                'Next


                'Me.AddPosts(Posts)

            End Sub

            Public Sub AddPosts(Posts As List(Of Task_Post))

                DB.InitMultiRowsInsert()
                For Each p In Posts
                    p.Task_Send_Id = Me.Id
                    DB.InsertRowOnSubmit(p)
                Next
                DB.SubmitChanges()


            End Sub

            Public Sub ResetAllPosts()

                Me.Tab_Task_Post.
                    Update.UpdateValue(
                        "send_post", 0
                ).ExecuteCommand()

            End Sub
            Public Sub DeleteAllPosts()

                Me.Tab_Task_Post.Delete.ExecuteCommand()

            End Sub
            Public Sub Close()

                Me.Next_Send_Date = Date.MinValue
                Me.Next_Send_Post = ""
                Me.Next_Send_Task_Scheduler_Id = 0

            End Sub

            'Public Sub SetNextSend()

            '    Dim d = GetNextSendDate()

            '    'Me.Active_Task = d > Date.UtcNow



            'End Sub


            Public ReadOnly Property Tab_Task_Post() As BuildQuery(Of Task_Post)
                Get
                    Return DB.TAB.Task_Post.BY.Task_Post.Task_Send_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Task_Scheduler() As BuildQuery(Of Task_Scheduler)
                Get
                    Return DB.TAB.Task_Scheduler.BY.Task_Scheduler.Task_Send_Id(Me.Id)
                End Get
            End Property


        End Class


        Partial Public Class _Trend

            Public Enum Type
                POST_ABS = 1
                FOLLOWER_ABS = 2
                MESSAGE_REL = 3
                SHARE_REL = 4
                ENGAGEMENT_REL = 5
                IMPRESSION_REL = 6
                AUTO_FOLLOW_ACCOUNT = 7
                AUTO_FOLLOW_BECOME_FOLLOWER = 8
                AUTO_FOLLOW_NOT_FOLLOWER = 9
                POST_REL = 10
                STATUS_FAKE = 11
                STATUS_INACTIVE = 12
                STATUS_LOW_ACTIVITY = 13
                STATUS_MEDIUM_ACTIVITY = 14
                STATUS_HIGHT_ACTIVITY = 15
                REPLY_REL = 16
                FOLLOWER_REL = 17
                UNFOLLOWER_REL = 18

            End Enum

        End Class

        Partial Public Class User

            Public Overrides Function ToString() As String

                Return SF("'{0}' [{1}]", Me.Surname, Me.Id)

            End Function

            Public ReadOnly Property Tab_User_Alert() As BuildQuery(Of User_Alert)
                Get
                    Return DB.TAB.User_Alert.BY.User_Alert.User_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property View_Alert() As BuildQuery(Of Alert)
                Get
                    Return DB.TAB.Alert.REL.Alert.User_Alert.BY.User_Alert.User_Id(Me.Id)
                End Get
            End Property


            Public ReadOnly Property Tab_User_Account() As BuildQuery(Of User_Account)
                Get
                    Return DB.TAB.User_Account.BY.User_Account.User_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_User_Account(AccountID As Integer) As BuildQuery(Of User_Account)
                Get
                    Return DB.TAB.User_Account.BY.User_Account.User_Id(Me.Id, AccountID)
                End Get
            End Property

            Public ReadOnly Property View_EnabledAccount() As BuildQuery(Of Account)
                Get
                    Return DB.TAB.Account.
                        REL.Account.Account_Auth.
                        REL.Account.User_Account.
                        BY.Account_Auth.Enabled.
                        BY.User_Account.User_Id(Me.Id)

                    'Return DB.VIEW.Account_UserEnabled.
                    '    BY.User_Account.User_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Group_Account() As BuildQuery(Of Group_Account)
                Get
                    Return DB.TAB.Group_Account.BY.Group_Account.User_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Group_Account(t As Integer) As BuildQuery(Of Group_Account)
                Get
                    Return DB.TAB.Group_Account.BY.Group_Account.User_Id(Me.Id, t)
                End Get
            End Property


            Public ReadOnly Property Tab_Folder() As BuildQuery(Of Folder)
                Get
                    Return DB.TAB.Folder.BY.Folder.User_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Folder(TypeId As mDB.Folder.Type, FolderParentId As Integer) As BuildQuery(Of Folder)
                Get
                    Return DB.TAB.Folder.BY.Folder.User_Id(Me.Id, TypeId, FolderParentId)
                End Get
            End Property

            Public ReadOnly Property Tab_User_Order() As BuildQuery(Of User_Order)
                Get
                    Return DB.TAB.User_Order.BY.User_Order.User_Id(Me.Id)
                End Get
            End Property

            Public ReadOnly Property Tab_User_Plan() As BuildQuery(Of User_Plan)
                Get
                    Return DB.TAB.User_Plan.BY.User_Plan.User_Id(Me.Id)
                End Get
            End Property
            Public Function View_User_Plan() As BuildQuery(Of User_Plan)
                Return DB.TAB.User_Plan.REL.User_Plan.Plan.BY.User_Plan.User_Id(Me.Id)
            End Function


            Public ReadOnly Property Tab_User_Promo() As BuildQuery(Of User_Promo)
                Get
                    Return DB.TAB.User_Promo.BY.User_Promo.User_Id(Me.Id)
                End Get
            End Property
            Public Function View_User_Promo() As BuildQuery(Of User_Promo)
                Return DB.TAB.User_Promo.REL.User_Promo.Promo.BY.User_Promo.User_Id(Me.Id)
            End Function


            Public ReadOnly Property Tab_Profile() As BuildQuery(Of Profile)
                Get
                    Return DB.TAB.Profile.
                        REL.Profile.Folder.
                        BY.Folder.User_Id(Me.Id)
                End Get
            End Property
            Public ReadOnly Property Tab_Profile(FolderId As Integer) As BuildQuery(Of Profile)
                Get
                    Return DB.TAB.Profile.
                        REL.Profile.Folder.
                        BY.Folder.Ref_Id(FolderId).
                        BY.Folder.User_Id(Me.Id)
                End Get
            End Property

            'Public ReadOnly Property Tab_Query(n As App.NetworkType) As BuildQuery(Of Query)
            '    Get
            '        Return DB.TAB.Query.
            '            REL.Query.Folder.
            '            BY.Folder.User_Id(Me.Id, mDB.Folder.GetFolderType(Folder.FuncType.QUERY, n))
            '    End Get
            'End Property

            'Public ReadOnly Property Tab_Query(n As App.NetworkType, FolderId As Integer) As BuildQuery(Of Query)
            '    Get
            '        'Return DB.TAB.Query.BY.Query.UserId(Me.Id, QueryTypeId, FolderId)
            '        Return DB.TAB.Query.
            '            REL.Query.Folder.
            '            BY.Folder.Ref_Id(FolderId).
            '            BY.Folder.User_Id(Me.Id, mDB.Folder.GetFolderType(Folder.FuncType.QUERY, n))
            '    End Get
            'End Property

            Public ReadOnly Property Tab_Categorize() As BuildQuery(Of Categorize)
                Get
                    Return DB.TAB.Categorize.
                        REL.Categorize.Folder.
                    BY.Folder.User_Id(Me.Id)

                End Get
            End Property
            Public ReadOnly Property Tab_Categorize(FolderId As Integer) As BuildQuery(Of Categorize)
                Get
                    Return DB.TAB.Categorize.
                        REL.Categorize.Folder.
                        BY.Folder.Ref_Id(FolderId).
                        BY.Folder.User_Id(Me.Id)
                End Get
            End Property
            'Public ReadOnly Property Tab_Categorize(n As App.NetworkType) As BuildQuery(Of Categorize)
            '    Get
            '        Return DB.TAB.Categorize.
            '            REL.Categorize.Folder.
            '        BY.Folder.User_Id(Me.Id, mDB.Folder.GetFolderType(Folder.FuncType.CATEGORIZE, n))

            '    End Get
            'End Property

            'Public ReadOnly Property Tab_Categorize(n As App.NetworkType, FolderId As Integer) As BuildQuery(Of Categorize)
            '    Get
            '        Return DB.TAB.Categorize.
            '            REL.Categorize.Folder.
            '            BY.Folder.Ref_Id(FolderId).
            '            BY.Folder.User_Id(Me.Id, mDB.Folder.GetFolderType(Folder.FuncType.CATEGORIZE, n))
            '    End Get
            'End Property

            Public Function View_Query() As BuildQuery(Of Query)
                Return DB.TAB.Query.
                    REL.Query.Folder.
                    BY.Folder.User_Id(Me.Id)
            End Function

            Public Function View_Query(FolderId As Integer) As BuildQuery(Of Query)
                'Return DB.TAB.Query.BY.Query.UserId(Me.Id, QueryTypeId, FolderId)
                Return DB.TAB.Query.
                    REL.Query.Folder.
                    BY.Folder.Ref_Id(FolderId).
                    BY.Folder.User_Id(Me.Id)

            End Function

            Private Function AddDefaultFolder(f As mDB.Folder.Type) As mDB.Folder

                Dim Folder = Me.Tab_Folder(f, 0).ToObj
                If Folder Is Nothing Then
                    Folder = New Folder With {.Folder = "ROOT", .User_Id = Me.Id, .Folder_Parent_Id = 0, .Folder_Type_Id = f}
                    Folder.InsertOnSubmit(DB)
                    'DB.TAB.Folder.InsertOnSubmit(Folder)
                    DB.SubmitChanges()
                End If

                Return Folder

            End Function

            Public Sub InitUserDataDB()

                AddDefaultFolder(Folder.Type.TWITTER_QUERY)
                AddDefaultFolder(Folder.Type.TWITTER_CATEGORIZE)
                AddDefaultFolder(Folder.Type.FACEBOOK_QUERY)
                AddDefaultFolder(Folder.Type.FACEBOOK_CATEGORIZE)
                AddDefaultFolder(Folder.Type.GOOGLE_QUERY)
                AddDefaultFolder(Folder.Type.GOOGLE_CATEGORIZE)


                'Dim FolderQuery = Me.Tab_Folder(mDB.Folder.Type.QUERY, 0).ToObj
                'If FolderQuery Is Nothing Then
                '    FolderQuery = New Folder With {.Folder = "ROOT", .User_Id = Me.Id, .Folder_Parent_Id = 0, .Folder_Type_Id = mDB.Folder.Type.QUERY}
                '    FolderQuery.InsertOnSubmit(DB)
                '    'DB.TAB.Folder.InsertOnSubmit(Folder)
                '    DB.SubmitChanges()
                'End If

                'Dim FolderCat = Me.Tab_Folder(mDB.Folder.Type.CATEGORIZE, 0).ToObj
                'If FolderCat Is Nothing Then
                '    FolderCat = New Folder With {.Folder = "ROOT", .User_Id = Me.Id, .Folder_Parent_Id = 0, .Folder_Type_Id = mDB.Folder.Type.CATEGORIZE}
                '    FolderCat.InsertOnSubmit(DB)
                '    'DB.TAB.Folder.InsertOnSubmit(Folder)
                '    DB.SubmitChanges()
                'End If

                'Dim PrivateCat = Me.Tab_Folder(mDB.Folder.Type.PRIVATE_MESSAGE, 0).ToObj
                'If PrivateCat Is Nothing Then
                '    PrivateCat = New Folder With {.Folder = "ROOT", .User_Id = Me.Id, .Folder_Parent_Id = 0, .Folder_Type_Id = mDB.Folder.Type.PRIVATE_MESSAGE}
                '    PrivateCat.InsertOnSubmit(DB)
                '    DB.SubmitChanges()

                '    Dim f = New Folder With {.Folder = "Inbox", .User_Id = Me.Id, .Folder_Parent_Id = PrivateCat.Id, .Folder_Type_Id = mDB.Folder.Type.PRIVATE_MESSAGE}
                '    f.InsertOnSubmit(DB)
                '    DB.SubmitChanges()

                '    f = New Folder With {.Folder = "Sent", .User_Id = Me.Id, .Folder_Parent_Id = PrivateCat.Id, .Folder_Type_Id = mDB.Folder.Type.PRIVATE_MESSAGE}
                '    f.InsertOnSubmit(DB)
                '    DB.SubmitChanges()

                'End If

            End Sub

            Private _User_Option As User_Option
            Public ReadOnly Property User_Option() As User_Option
                Get
                    If _User_Option Is Nothing Then
                        _User_Option = DB.TAB.User_Option.GetByPK(Me.Id)
                        If _User_Option Is Nothing Then
                            _User_Option = New User_Option With {.User_Id = Me.Id}
                            DB.InsertOnSubmit(_User_Option)
                            DB.SubmitChanges()
                        End If
                    End If
                    Return _User_Option
                End Get
            End Property

            Private _CurrAccount As mDB.Account
            Public ReadOnly Property CurrAccount() As Account
                Get
                    If _CurrAccount Is Nothing Then
                        _CurrAccount = Me.View_EnabledAccount.GetByPK(Me.Session.CurrAccount)
                    End If
                    Return _CurrAccount
                End Get
            End Property

            Private _print As MyUI.Print2
            Public Property Print() As MyUI.Print2
                Get
                    If _print Is Nothing Then
                        _print = New MyUI.Print2(Me.UtcOffset)
                    End If
                    Return _print
                End Get
                Set(ByVal value As MyUI.Print2)
                    _print = value
                End Set
            End Property

            Private _timezone As mDB.Time_Zone
            Public ReadOnly Property TimeZone() As mDB.Time_Zone
                Get
                    If _timezone Is Nothing Then
                        _timezone = DB.TAB.Time_Zone.GetByPK(Me.Time_Zone_Id)
                    End If
                    Return _timezone
                End Get
            End Property

            Public ReadOnly Property UtcOffset As Integer
                Get
                    Return Me.TimeZone.TimeZoneInf.BaseUtcOffset.TotalSeconds
                End Get
            End Property

#Region "Date"

            Public Function LDate(UtcDate As Date) As Date
                Return UtcDate.AddSeconds(Me.UtcOffset)
            End Function

            Public Function UtcDate(LDate As Date) As Date
                Return LDate.AddSeconds(-Me.UtcOffset)
            End Function


#End Region



            Private _CurrGroup As Group_Account
            Public ReadOnly Property CurrGroup() As Group_Account
                Get
                    If _CurrGroup Is Nothing Then
                        If Me.Session.ActiveGroup Then
                            If Me.Session.CurrGroup = 0 Then
                                _CurrGroup = Me.Tab_Group_Account(1).ToObj
                                If _CurrGroup Is Nothing Then
                                    _CurrGroup = New mDB.Group_Account With {
                                        .Group_Type_Id = 1, .User_Id = Me.Id, .Account_Ids = New List(Of Integer)
                                    }
                                    DB.TAB.Group_Account.InsertOnSubmit(_CurrGroup)
                                    DB.SubmitChanges()
                                End If
                            Else
                                _CurrGroup = DB.TAB.Group_Account.GetByPK(Me.Session.CurrGroup)
                            End If
                            Me.Session.CurrGroup = _CurrGroup.Id

                            If _CurrGroup.Account_Ids.Count = 0 Then
                                _CurrGroup.Account_Ids.Add(Me.CurrAccount.Id)
                            End If
                        Else
                            _CurrGroup = New mDB.Group_Account(New List(Of Account) From {Me.CurrAccount})
                        End If
                    End If
                    Return _CurrGroup
                End Get
            End Property



#Region "SESSIONE SU DB"


            'Private _SessionData As Dictionary(Of String, Object)
            'Public Property SessionData() As Dictionary(Of String, Object)
            '    Get
            '        If _SessionData Is Nothing Then
            '            _SessionData = MyApp.JSONDeserializeObj(Of Dictionary(Of String, Object))(Me._Session_Data_Json)
            '        End If
            '        Return _SessionData
            '    End Get
            '    Set(value As Dictionary(Of String, Object))
            '        Me._SessionData = MyApp.GetSetDataJson(value, Me.Session_Data_Json)
            '    End Set
            'End Property


            'Private _SaveSession As Boolean = False
            'Public Property Session(key As SessionKey) As Object
            '    Get
            '        'If _SessionData Is Nothing Then
            '        '    LoadSession()
            '        'End If

            '        Dim SessionValue As Object
            '        If Me.SessionData.ContainsKey(key.ToString) Then
            '            SessionValue = _SessionData(key.ToString)
            '        Else
            '            SessionValue = User.DefaultVar(key)
            '        End If

            '        Return SessionValue

            '    End Get
            '    Set(value As Object)

            '        Me.SessionData(key.ToString) = value
            '        _SaveSession = True

            '    End Set
            'End Property


            'Public Enum SessionKey

            '    CURR_ACC = 0
            '    LAST_VIEW_ALERT_ID = 1
            '    CURR_ACCS = 2
            'End Enum

            'Public Sub ResetSession()

            '    'user.Session(VariableType.CURR_ACC) = DefaultVar(VariableType.CURR_ACC)
            '    'Me.SaveSessionData()

            'End Sub
            'Public Shared Function DefaultVar(key As SessionKey) As Object
            '    Dim SessionValue As Object

            '    Select Case key
            '        Case SessionKey.CURR_ACC
            '            SessionValue = 0
            '        Case SessionKey.CURR_ACCS
            '            SessionValue = New List(Of Integer) From {0}
            '        Case Else
            '            SessionValue = ""
            '    End Select

            '    Return SessionValue

            'End Function
            Private _session As SessionUser
            Public Property Session() As SessionUser
                Get
                    If _session Is Nothing Then
                        _session = MyApp.JSONDeserializeObj(Of SessionUser)(Me.Session_Json)
                    End If
                    Return _session
                End Get
                Set(value As SessionUser)
                    Me._session = MyApp.GetSetDataJson(value, Me.Session_Json)
                End Set
            End Property

            Public Sub SessionSave()

                Me.Session = Me.Session
                'Me.Session_Data_Json = MyApp.JSONSerialize(Me.SessionData)
                'Data_Json.SaveObj(DB, Me.Session_Data_Id, Me.SessionData)
                DB.SubmitChanges()

            End Sub

            Public Class SessionUser
                Public Property CurrAccount As Integer
                Public Property CurrGroup As Integer
                Public Property CurrPage As String
                'Public Property CurrAccounts As New List(Of Integer)
                'Public Property LastViewAlert As Integer
                Public Property ActiveGroup As Boolean
                'Public Property ListenBox As List(Of Integer)
                'Public Property ListenHasgtag As List(Of Integer)
                Public Property Listen As New SessionListen
                Public Property Alert As New SessionAlert

                Public Class SessionListen
                    Public Property Box As New List(Of Integer) From {1, 2}
                    Public Property Hasgtag As New List(Of Integer)
                End Class

                Public Class SessionAlert
                    Public Property LastViewID As Integer
                    Public Property LastDownload As Integer
                    Public Property Count As Integer
                End Class

            End Class
#End Region

#Region "GESTIONE PIANI PROMO"


            Public Function View_CurrUserPlains() As BuildQuery(Of User_Plan)


                Return View_CurrUserPlains(-1)

            End Function

            Public Function View_CurrUserPlains(PlanTypeID As Integer) As BuildQuery(Of User_Plan)

                Dim q = Me.View_User_Plan

                If PlanTypeID <> -1 Then
                    q.BY.Plan.Plan_Type_Id(PlanTypeID)
                End If

                q.Where("plan_begin_date", "<", Date.UtcNow)
                q.OrderBy("plan_begin_date desc")

                Return q

            End Function

            Public Function GetCurrUserPromo(PlanID As Integer) As User_Promo

                Return Me.View_User_Promo.
                    Where("promo_begin_date", "<", Date.UtcNow, "promo_expire_date", ">", Date.UtcNow.AddDays(1)).
                    Where("plan_id", "=", PlanID).
                ToObj

            End Function

            Private _curr_user_promo As User_Promo
            Public ReadOnly Property CurrUserpromo() As User_Promo
                Get
                    If _curr_user_promo Is Nothing Then
                        _curr_user_promo = Me.GetCurrUserPromo(Me.Plan.Id)
                    End If
                    Return _curr_user_promo
                End Get
            End Property

            Private _curr_user_plan As User_Plan
            Public Property CurrUserPlan() As User_Plan
                Get
                    If _curr_user_plan Is Nothing Then
                        _curr_user_plan = Me.View_CurrUserPlains(1).Limit(1).ToObj
                    End If
                    Return _curr_user_plan
                End Get
                Set(value As User_Plan)
                    _curr_user_plan = value
                End Set
            End Property


            Private _plan As Plan
            Public ReadOnly Property Plan() As Plan
                Get
                    Return CurrUserPlan.Plan
                End Get
            End Property

            Private _Promo As Promo
            Public ReadOnly Property Promo() As Promo
                Get
                    If CurrUserpromo Is Nothing Then
                        Return Nothing
                    Else
                        Return CurrUserpromo.Promo
                    End If
                End Get
            End Property

            Public Function GetCurrPrice(Num As Integer) As Double

                Dim Price As Double = -1


                If Me.Plan IsNot Nothing Then
                    Price = Plan.Getprice(Num)
                End If


                If Me.Promo IsNot Nothing Then
                    Price = Promo.Getprice(Price)
                End If

                Return Price

            End Function
            Public Function GetpriceUpgrade(Num As Integer, planid As Integer, promoid As Integer) As Double

                Dim newplan = DB.TAB.Plan.GetByPK(planid)
                Dim newpromo = DB.TAB.Promo.GetByPK(promoid)
                Dim Newprice = newplan.Getprice(Num)

                Dim price As Double

                If newpromo IsNot Nothing Then
                    If newpromo.Plan_Ids.IndexOf(planid) <> -1 Then
                        Newprice = newpromo.Getprice(Newprice)
                    End If
                End If

                If Me.CurrUserPlan Is Nothing Then

                    price = Newprice

                Else

                    If Me.CurrUserPlan.Plan_Expire_Date < Date.UtcNow Then

                        price = Newprice

                    Else

                        If newplan.Price_Month = Me.Plan.Price_Month Then
                            price = Newprice
                        Else
                            If newplan.Price_Month > Me.Plan.Price_Month Then
                                ' UPGRADE
                                'Dim newprice = Niewprice


                                Dim lastorder = Me.Tab_User_Order.
                                    Where("processed", "=", True).
                                    OrderBy("processed_date desc").
                                    Limit(10).ToList

                                Dim expdate = Me.CurrUserPlan.Plan_Expire_Date
                                Dim tot = 0

                                For Each order In lastorder
                                    If expdate < Date.UtcNow Then
                                        Exit For
                                    End If

                                    expdate = expdate.AddMonths(-order.Plan_Month)
                                    tot += order.Amount

                                Next

                                price = Newprice - (tot / DateDiff(DateInterval.Day, expdate, Me.CurrUserPlan.Plan_Expire_Date) * DateDiff(DateInterval.Day, Date.UtcNow, Me.CurrUserPlan.Plan_Expire_Date))

                            Else
                                'DOWNGRADE
                                price = 0

                            End If

                        End If

                    End If
                End If




                Return price

            End Function

            Public Function IsPromoUsed(PromoID As Integer) As Boolean

                Dim pp = Me.Tab_User_Order.
                    Where("processed", "=", True).
                    Where("promo_id", "=", PromoID).ToObj

                Return pp IsNot Nothing


            End Function

            Public Sub Createorder(order As User_Order)

                DB.TAB.User_Order.InsertOnSubmit(order)

                order.User_Id = Me.Id
                order.Create_Data = Date.UtcNow

                DB.SubmitChanges()

            End Sub

            Public Function LimitPlan(l As mDB.Plan.LimitType, ParamArray p() As Object) As Boolean

                Dim limit = True

                Select Case l
                    Case Plan.LimitType.ACCOUNT_PER_USER
                        Dim tot = Me.View_EnabledAccount.ToList.Count
                        limit = tot >= Me.Plan.Account_Per_User

                    Case Plan.LimitType.FOLLOWER_PER_USER
                        Dim tot = Me.View_EnabledAccount.REL.Account.Account_Update.SetSelect("sum(follower_count)").ToObj(Of Integer)()
                        If p.Length > 0 Then
                            tot += Me.View_EnabledAccount.GetByPK(p(0)).Account_Add_Info.Follower_Count
                        End If
                        limit = tot >= Me.Plan.Follower_Analysis_Per_User

                    Case Plan.LimitType.FOLLOWER_ANALYSIS_PER_USER
                        Dim tot = Me.View_EnabledAccount.
                            REL.Account.Account_Add_Info.
                            BY.Account_Auth.AnalysisFollower.
                            SetSelect("sum(follower_count)").
                        ToObj(Of Integer)()

                        If p.Length > 0 Then
                            tot += Me.View_EnabledAccount.GetByPK(p(0)).Account_Add_Info.Follower_Count
                        End If

                        limit = tot >= Me.Plan.Follower_Analysis_Per_User



                    Case Plan.LimitType.QUERY_PER_USER
                        Dim tot = Me.View_Query.SetSelect("count(*)").ToObj(Of Integer)()
                        limit = tot >= Me.Plan.Query_Per_User

                    Case Plan.LimitType.LISTEN_PER_ACCOUNT
                        Dim tot = Me.View_EnabledAccount.GetByPK(p(0)).Tab_Listen_Query.SetSelect("count(*)").ToObj(Of Integer)()
                        limit = tot >= Me.Plan.Listen_Per_Account

                    Case GloukDB.Plan.LimitType.AUTO_FOLLOWER_PER_ACCOUNT
                        Dim tot = Me.View_EnabledAccount.GetByPK(p(0)).Tab_Auto_Follow_Query.SetSelect("count(*)").ToObj(Of Integer)()
                        tot += Me.View_EnabledAccount.GetByPK(p(0)).Tab_Auto_Follow_Profile.SetSelect("count(*)").ToObj(Of Integer)()
                        limit = tot >= Me.Plan.Auto_Follower_Per_Account

                End Select


                Return limit

            End Function


#End Region

            Public Class Options

            End Class

        End Class

        Partial Public Class User_Option

            Private _Options As User.Options
            Public Property Options() As User.Options
                Get
                    If _Options Is Nothing Then
                        _Options = MyApp.JSONDeserializeObj(Of User.Options)(Me.Options_Json)
                    End If
                    Return _Options
                End Get
                Set(value As User.Options)
                    Me._Options = MyApp.GetSetDataJson(value, Me.Options_Json)
                End Set
            End Property


        End Class

        Partial Public Class User_Order

            Private _User As mDB.User
            Public ReadOnly Property User() As User
                Get
                    If _User Is Nothing Then
                        _User = DB.TAB.User.GetByPK(Me.User_Id)
                    End If
                    Return _User
                End Get
            End Property
            Private _plan As Plan
            Public ReadOnly Property Plan() As Plan
                Get
                    If _plan Is Nothing Then
                        _plan = DB.TAB.Plan.GetByPK(Me.Plan_Id)
                    End If
                    Return _plan
                End Get
            End Property

            Private _Promo As Promo
            Public ReadOnly Property Promo() As Promo
                Get
                    If _Promo Is Nothing Then
                        _Promo = DB.TAB.Promo.GetByPK(Me.Promo_Id)
                    End If
                    Return _Promo
                End Get
            End Property

            Public Sub Process()

                DB.TransactionStart()

                '------------------------------------------------------------
                ' PIANO
                '------------------------------------------------------------

                If Me.Plan_Id <> 0 Then
                    Dim CreateNew = False

                    'verifica se esiste già il piano
                    Dim Currplan = Me.User.View_CurrUserPlains(Me.Plan.Plan_Type_Id).ToObj

                    'se non esiste o ho detto di crearne uno nuovo
                    If Currplan Is Nothing Then
                        CreateNew = True
                    Else
                        If Currplan.Plan_Id <> Me.Plan.Id Then
                            CreateNew = True
                        End If

                        'elimino gli eventuali downgrade
                        Dim DownPlan = Me.User.View_User_Plan.
                            BY.Plan.Plan_Type_Id(Me.Plan.Plan_Type_Id).
                            Where("plan_begin_date", ">", Currplan.Plan_Begin_Date).
                        ToObj
                        If DownPlan IsNot Nothing Then
                            DB.DeleteOnSubmit(DownPlan)
                            DB.SubmitChanges()
                        End If

                    End If
                    If Me.Plan_Create Then
                        CreateNew = True
                    End If


                    If CreateNew Then

                        Dim NewPlan = New mDB.User_Plan With {
                            .User_Id = Me.User_Id, .Plan_Id = Me.Plan_Id, .Plan_Month = Me.Plan_Month,
                            .Plan_Begin_Date = Date.UtcNow, .Plan_Expire_Date = Date.UtcNow.AddMonths(Me.Plan_Month).Date
                        }

                        If Currplan IsNot Nothing Then
                            'verifica che il corrente sia ancora attivo
                            If Currplan.Plan_Expire_Date > Date.UtcNow Then

                                Dim Upgrade = Currplan.Plan.Price_Month < Me.Plan.Price_Month
                                Dim Downgrade = Currplan.Plan.Price_Month > Me.Plan.Price_Month

                                ' se si fa un down il nuovo piano iniziera quando finisce quello in corso
                                If Downgrade Then

                                    NewPlan.Plan_Begin_Date = Currplan.Plan_Expire_Date
                                    NewPlan.Plan_Expire_Date = Currplan.Plan_Expire_Date.Date

                                    'Currplan.Plan_Expire_Date = Currplan.Plan_Active_Date
                                Else
                                    ' altrimenti il vecchio piano finisce ora
                                    Currplan.Plan_Expire_Date = Date.UtcNow
                                End If

                                DB.SubmitChanges()
                            End If

                        End If

                        DB.TAB.User_Plan.InsertOnSubmit(NewPlan)
                        DB.SubmitChanges()

                    Else

                        'accoda a quello precedente
                        Currplan.Plan_Month = Me.Plan_Month
                        If Currplan.Plan_Expire_Date < Date.UtcNow Then
                            Currplan.Plan_Expire_Date = Date.UtcNow
                        End If
                        Currplan.Plan_Expire_Date = Currplan.Plan_Expire_Date.AddMonths(Me.Plan_Month).Date

                        DB.SubmitChanges()

                    End If
                End If

                '------------------------------------------------------------
                ' PROMO
                '------------------------------------------------------------

                If Me.Promo_Id <> 0 Then

                    ' verifica se già esiste la promo associata allo stesso piano
                    Dim CurrPromo = Me.User.GetCurrUserPromo(Me.Plan.Id)
                    Dim CreateNew = False

                    If Me.Promo_Create Then
                        CreateNew = True
                    Else
                        If CurrPromo Is Nothing Then
                            CreateNew = True
                        Else
                            'se cmq il codice è diverso crea un nuova
                            CreateNew = CurrPromo.Promo_Id <> Me.Promo_Id
                        End If
                    End If

                    Dim Promo_Expire_Date As Date

                    If CreateNew Then

                        Dim UserPromo = New mDB.User_Promo With {
                            .User_Id = Me.User_Id, .Promo_Id = Me.Promo_Id, .Plan_Id = Me.Plan_Id,
                            .Promo_Begin_Date = Date.UtcNow, .Promo_Expire_Date = Date.UtcNow.AddMonths(Me.Promo_Month).Date
                        }

                        If CurrPromo IsNot Nothing Then
                            CurrPromo.Promo_Expire_Date = Date.UtcNow
                            DB.SubmitChanges()

                        End If

                        DB.TAB.User_Promo.InsertOnSubmit(UserPromo)
                        DB.SubmitChanges()

                        Promo_Expire_Date = UserPromo.Promo_Expire_Date

                    Else

                        '    'accoda
                        If CurrPromo.Promo_Expire_Date < Date.UtcNow Then
                            CurrPromo.Promo_Expire_Date = Date.UtcNow
                        End If

                        CurrPromo.Promo_Expire_Date = CurrPromo.Promo_Expire_Date.AddMonths(Me.Plan_Month).Date
                        DB.SubmitChanges()

                        Promo_Expire_Date = CurrPromo.Promo_Expire_Date

                    End If

                End If





                '------------------------------------------------------------
                ' CONTROLLI CORRETTEZZA
                '------------------------------------------------------------

                Dim FinalPromo = Me.User.GetCurrUserPromo(Me.Plan.Id)
                If FinalPromo IsNot Nothing Then
                    If FinalPromo.Promo.Plan_Ids.IndexOf(Me.Plan_Id) = -1 Then
                        FinalPromo.Promo_Expire_Date = Date.UtcNow
                        DB.SubmitChanges()
                    End If
                End If

                Me.Processed_Date = Date.UtcNow
                Me.Processed = True

                DB.SubmitChanges()

                DB.TransactionCommit()

            End Sub

            'Public Sub Process()

            '    DB.TransactionStart()

            '    '------------------------------------------------------------
            '    ' PIANO
            '    '------------------------------------------------------------

            '    If Me.Plan_Id <> 0 Then
            '        Dim CreateNew = False

            '        'verifica se esiste già il piano
            '        Dim Currplan = Me.User.View_CurrUserPlains(Me.Plan.Plan_Type_Id).ToObj

            '        'se non esiste o ho detto di crearne uno nuovo
            '        If Currplan Is Nothing Then
            '            CreateNew = True
            '        Else
            '            If Currplan.Plan_Id <> Me.Plan.Id Then
            '                CreateNew = True
            '            End If

            '            'elimino gli eventuali downgrade
            '            Dim DownPlan = Me.User.View_User_Plan.
            '                BY.Plan.Plan_Type_Id(Me.Plan.Plan_Type_Id).
            '                Where("plan_begin_date", ">", Currplan.Plan_Begin_Date).
            '            ToObj
            '            If DownPlan IsNot Nothing Then
            '                DB.DeleteOnSubmit(DownPlan)
            '                DB.SubmitChanges()
            '            End If

            '        End If
            '        If Me.Plan_Create Then
            '            CreateNew = True
            '        End If


            '        If CreateNew Then

            '            Dim NewPlan = New mDB.User_Plan With {
            '                .User_Id = Me.User_Id, .Plan_Id = Me.Plan_Id, .Plan_Month = Me.Plan_Month,
            '                .Plan_Begin_Date = Date.UtcNow, .Plan_Expire_Date = Date.UtcNow.AddMonths(Me.Plan_Month).Date
            '            }

            '            If Currplan IsNot Nothing Then

            '                Dim Upgrade = Currplan.Plan.Price_Month < Me.Plan.Price_Month
            '                Dim Downgrade = Currplan.Plan.Price_Month > Me.Plan.Price_Month

            '                ' se si fa un down il nuovo piano iniziera quando finisce quello in corso
            '                If Downgrade Then

            '                    NewPlan.Plan_Begin_Date = Currplan.Plan_Expire_Date
            '                    NewPlan.Plan_Expire_Date = Currplan.Plan_Expire_Date.Date

            '                    'Currplan.Plan_Expire_Date = Currplan.Plan_Active_Date
            '                Else
            '                    ' altrimenti il vecchio piano finisce ora
            '                    Currplan.Plan_Expire_Date = Date.UtcNow
            '                End If

            '                DB.SubmitChanges()

            '            End If

            '            DB.TAB.User_Plan.InsertOnSubmit(NewPlan)
            '            DB.SubmitChanges()


            '        Else

            '            'accoda a quello precedente
            '            Currplan.Plan_Month = Me.Plan_Month
            '            If Currplan.Plan_Expire_Date < Date.UtcNow Then
            '                Currplan.Plan_Expire_Date = Date.UtcNow
            '            End If
            '            Currplan.Plan_Expire_Date = Currplan.Plan_Expire_Date.AddMonths(Me.Plan_Month).Date

            '            DB.SubmitChanges()

            '        End If
            '    End If

            '    '------------------------------------------------------------
            '    ' PROMO
            '    '------------------------------------------------------------

            '    If Me.Promo_Id <> 0 Then

            '        Dim usepromo = True

            '        'verifica se si può riutilizzare
            '        If Me.Promo.Use_Once Then
            '            If Me.User.IsPromoUsed(Me.Promo_Id) Then
            '                usepromo = False
            '            End If
            '        End If

            '        ' verifica se la promo si può usare per questo piano
            '        If Me.Promo.Plan_Ids.IndexOf(Me.Plan_Id) = -1 Then
            '            usepromo = False
            '        End If

            '        If usepromo Then

            '            ' verifica se già esiste la promo associata allo stesso piano
            '            Dim CurrPromo = Me.User.GetCurrUserPromo(Me.Plan.Id)
            '            Dim CreateNew = False

            '            If Me.Promo_Create Then
            '                CreateNew = True
            '            Else
            '                If CurrPromo Is Nothing Then
            '                    CreateNew = True
            '                Else
            '                    'se cmq il codice è diverso crea un nuova
            '                    CreateNew = CurrPromo.Promo_Id <> Me.Promo_Id
            '                End If
            '            End If

            '            Dim Promo_Expire_Date As Date

            '            If CreateNew Then

            '                Dim UserPromo = New mDB.User_Promo With {
            '                    .User_Id = Me.User_Id, .Promo_Id = Me.Promo_Id, .Plan_Id = Me.Plan_Id,
            '                    .Promo_Begin_Date = Date.UtcNow, .Promo_Expire_Date = Date.UtcNow.AddMonths(Me.Promo_Month).Date
            '                }

            '                If CurrPromo IsNot Nothing Then
            '                    CurrPromo.Promo_Expire_Date = Date.UtcNow
            '                    DB.SubmitChanges()

            '                End If

            '                DB.TAB.User_Promo.InsertOnSubmit(UserPromo)
            '                DB.SubmitChanges()

            '                Promo_Expire_Date = UserPromo.Promo_Expire_Date

            '            Else

            '                '    'accoda
            '                CurrPromo.Promo_Expire_Date = CurrPromo.Promo_Expire_Date.AddMonths(Me.Plan_Month).Date
            '                DB.SubmitChanges()

            '                Promo_Expire_Date = CurrPromo.Promo_Expire_Date

            '            End If

            '            'If Me.Promo.Discount_Perc_Month = 100 Or Me.Promo.Price_Month = 0 Then
            '            '    Dim Currplan = Me.User.View_CurrUserPlains(Me.Plan.Plan_Type_Id).ToObj
            '            '    Currplan.Plan_Expire_Date = Promo_Expire_Date
            '            '    DB.SubmitChanges()
            '            'End If


            '        End If


            '    End If


            '    '------------------------------------------------------------
            '    ' CONTROLLI CORRETTEZZA
            '    '------------------------------------------------------------

            '    Dim FinalPromo = Me.User.GetCurrUserPromo(Me.Plan.Id)
            '    If FinalPromo IsNot Nothing Then
            '        If FinalPromo.Promo.Plan_Ids.IndexOf(Me.Plan_Id) = -1 Then
            '            FinalPromo.Promo_Expire_Date = Date.UtcNow
            '            DB.SubmitChanges()
            '        End If
            '    End If

            '    Me.Processed_Date = Date.UtcNow
            '    Me.Processed = True

            '    DB.SubmitChanges()

            '    DB.TransactionCommit()

            'End Sub

            Public Function Getprice(Num As Integer) As Double

                Dim Price = Me.Plan.Getprice(Num)

                If Me.Promo IsNot Nothing Then
                    Price = Promo.Getprice(Price)
                End If

                Return Price

            End Function



        End Class

        Partial Class User_Plan

            Private _plan As Plan
            Public ReadOnly Property Plan() As Plan
                Get
                    If _plan Is Nothing Then
                        _plan = DB.TAB.Plan.GetByPK(Me.Plan_Id)
                    End If
                    Return _plan
                End Get
            End Property


        End Class
        Partial Class User_Promo

            Private _promo As Promo
            Public ReadOnly Property Promo() As Promo
                Get
                    If _promo Is Nothing Then
                        _promo = DB.TAB.Promo.GetByPK(Me.Promo_Id)
                    End If
                    Return _promo
                End Get
            End Property


        End Class


        Partial Public Class Plan

            Public Enum LimitType
                ACCOUNT_PER_USER = 1
                FOLLOWER_PER_USER = 2
                FOLLOWER_ANALYSIS_PER_USER = 3
                QUERY_PER_USER = 4
                LISTEN_PER_ACCOUNT = 5
                AUTO_FOLLOWER_PER_ACCOUNT = 6
            End Enum

            Public Function Getprice(Num As Integer) As Double

                Dim Price = Me.Price_Month

                If Num >= 12 Then
                    Price = Price * 0.9D
                End If

                Return Price * Num

            End Function

        End Class

        Partial Class Promo

            Private _Plan_Ids As List(Of Integer)
            Public Property Plan_Ids() As List(Of Integer)
                Get
                    If _Plan_Ids Is Nothing Then
                        _Plan_Ids = MyApp.JSONDeserializeObj(Of List(Of Integer))(Me.Plan_Ids_Json)
                    End If
                    Return _Plan_Ids
                End Get
                Set(value As List(Of Integer))
                    Me._Plan_Ids = MyApp.GetSetDataJson(value, Me.Plan_Ids_Json)
                End Set
            End Property


            Public Function Getprice(price As Double) As Double


                If Me.Discount_Perc_Month <> 0 Then
                    price = price - (price / 100 * Me.Discount_Perc_Month)
                ElseIf Me.Discount_Abs_Month <> 0 Then
                    price = price - Me.Discount_Abs_Month
                ElseIf Me.Price_Month <> 0 Then
                    price = Me.Price_Month
                End If

                Return price

            End Function


            'Public Function Getprice(price As Double, Num As Integer, Interval As DateInterval) As Double


            '    Select Case Interval
            '        Case DateInterval.Month
            '            If Me.Discount_Perc_Month <> 0 Then
            '                price = price - (price / 100 * Me.Discount_Perc_Month)
            '            ElseIf Me.Discount_Abs_Month <> 0 Then
            '                price = price - Me.Discount_Abs_Month
            '            ElseIf Me.Price_Month <> 0 Then
            '                price = Me.Price_Month
            '            End If
            '        Case DateInterval.Year
            '            If Me.Discount_Perc_Year <> 0 Then
            '                price = price - (price / 100 * Me.Discount_Perc_Year)
            '            ElseIf Me.Discount_Abs_Year <> 0 Then
            '                price = price - Me.Discount_Abs_Year
            '            ElseIf Me.Price_Year <> 0 Then
            '                price = Me.Price_Year
            '            End If
            '    End Select

            '    Return price * Num

            'End Function


        End Class

        Partial Class Private_Post



        End Class

        Partial Class Private_Post_Last

            Public Enum type
                RECEIVE = 1
                SEND = 2
            End Enum


        End Class


        Partial Class Group_Query
            Implements IQueryAnalysis


            Public Sub New(QueryList As List(Of Query))
                Me._QueryList = QueryList
            End Sub


            Private _Query_Ids As List(Of Integer)
            Public Property Query_Ids() As List(Of Integer)
                Get
                    If _Query_Ids Is Nothing Then
                        _Query_Ids = MyApp.JSONDeserializeObj(Of List(Of Integer))(Me.Query_Ids_Json)
                    End If
                    Return _Query_Ids
                End Get
                Set(value As List(Of Integer))
                    Me._Query_Ids = MyApp.GetSetDataJson(value, Me.Query_Ids_Json)
                End Set
            End Property

            Public ReadOnly Property Tab_Query() As BuildQuery(Of Query)
                Get
                    Dim q = DB.TAB.Query

                    If Me.Query_Ids.Count = 0 Then
                        q.Where("id", "=", -1)
                    Else
                        q.Where("id", "IN", Me.Query_Ids)
                    End If
                    Return q
                End Get
            End Property

            Private _QueryList As List(Of Query)
            Public ReadOnly Property QueryList() As List(Of Query)
                Get
                    If _QueryList Is Nothing Then
                        _QueryList = Me.Tab_Query.ToList
                    End If
                    Return _QueryList
                End Get
                'Set(value As List(Of Query))
                '    _QueryList = value
                'End Set
            End Property
            Public Function GetTrendAccount(FromDate As Date, ToDate As Date) As List(Of _Query_Account) Implements IQueryAnalysis.GetTrendAccount

                Dim Trends = New List(Of _Query_Account)

                For Each q In Me.QueryList
                    Trends.AddRange(q.GetTrendAccount(FromDate, ToDate))
                Next

                Trends = (
                    From tr In Trends
                    Order By tr.Post_Update
                    Group tr By tr.Post_Update Into g = Group
                    Select New _Query_Account With {.Post_Update = Post_Update, .Post_Count = g.Sum(Function(o) o.Post_Count), .Account_Follower_Count = g.Sum(Function(o) o.Account_Follower_Count)}
                ).ToList

                Return Trends

            End Function

            Public Function View_Account_Search(FromDate As Date, ToDate As Date, Username As String) As DBase.MySql.SqlQuery(Of mDB._Query_Account)

                Dim qq = New List(Of DBase.MySql.SqlQuery(Of _Query_Account))

                For Each q In Me.QueryList

                    qq.Add(q.View_Account_Search(FromDate, ToDate, Username))

                Next

                Dim db = mDB.GetDB

                Return db.GetQuery(Of mDB._Query_Account).
                    From(db.UnionQuery(qq), "Query_Account", "")

            End Function

            Public Function GetLastPostFromQueries(Max As Integer) As List(Of mDB._Query_Post)

                Dim Posts As New List(Of mDB._Query_Post)
                Dim Lastdate As Date = Date.MinValue

                For Each q In Me.QueryList

                    Posts.AddRange(q._Tab_Query_Post.OrderBy("pubb_date desc").Limit(Max).ToList)
                    Posts = (From p In Posts Order By p.Pubb_Date Descending Take Max).ToList

                Next

                Return Posts

            End Function

        End Class
        Partial Class Group_Account
            Implements IAccountAnalysis

            Public Sub New(q As List(Of Account))
                Me._AccountList = q
            End Sub

            Private _Account_Ids As List(Of Integer)
            Public Property Account_Ids() As List(Of Integer)
                Get
                    If _Account_Ids Is Nothing Then
                        _Account_Ids = MyApp.JSONDeserializeObj(Of List(Of Integer))(Me.Account_Ids_Json)
                    End If
                    Return _Account_Ids
                End Get
                Set(value As List(Of Integer))
                    Me._Account_Ids = MyApp.GetSetDataJson(value, Me.Account_Ids_Json)
                End Set
            End Property

            Public ReadOnly Property Tab_Account() As BuildQuery(Of Account)
                Get
                    Dim q = DB.TAB.Account

                    If Me.Account_Ids.Count = 0 Then
                        q.Where("id", "=", -1)
                    Else
                        q.Where("id", "IN", Me.Account_Ids)
                    End If
                    Return q
                End Get
            End Property

            Private _AccountList As List(Of Account)
            Public ReadOnly Property AccountList() As List(Of Account)
                Get
                    If _AccountList Is Nothing Then
                        _AccountList = Me.Tab_Account.ToList
                    End If
                    Return _AccountList
                End Get
                'Set(value As List(Of Account))
                '    _AccountList = value
                'End Set
            End Property


#Region "Followers"

            Public Function GetFollowerAnalysisValue(AnalysisType As Follower_Analysis.Type, DataType As Integer) As Integer Implements IAccountAnalysis.GetFollowerAnalysisValue

                Dim Analysis = New List(Of Integer)

                For Each acc In Me.AccountList
                    Analysis.Add(acc.GetFollowerAnalysisValue(AnalysisType, DataType))
                Next

                Return Analysis.Sum

            End Function

            Public Function GetFollowerAnalysis(AnalysisType As Follower_Analysis.Type) As List(Of Follower_Analysis) Implements IAccountAnalysis.GetFollowerAnalysis

                Dim Analysis = New List(Of Follower_Analysis)

                For Each acc In Me.AccountList
                    Analysis.AddRange(acc.GetFollowerAnalysis(AnalysisType))
                Next

                Analysis = (
                    From tr In Analysis
                    Group tr By tr.Data_Type_Id Into g = Group
                    Select New mDB.Follower_Analysis With {.Data_Type_Id = Data_Type_Id, .Value = g.Sum(Function(o) o.Value)}
                ).ToList

                Return Analysis

            End Function

#End Region

#Region "Trend"

            Public Function GetTrendSum(t As _Trend.Type, fromDate As Date, ToDate As Date) As Integer Implements IAccountAnalysis.GetTrendSum

                'Return Me._Tab_Trend(t, fromDate, ToDate).SetSelect("sum(value)").ToObj(Of Integer)()
                Dim Trends = New List(Of Integer)

                For Each acc In Me.AccountList
                    Trends.Add(acc.GetTrendSum(t, fromDate, ToDate))
                Next

                Return Trends.Sum


            End Function

            Public Function GetTrendValue(t As _Trend.Type, D As Date) As Integer Implements IAccountAnalysis.GetTrendValue

                Dim Trends = New List(Of Integer)

                For Each acc In Me.AccountList
                    Trends.Add(acc.GetTrendValue(t, D))
                Next

                Return Trends.Sum

            End Function
            Public Function GetTrend(t As _Trend.Type, FromDate As Date, ToDate As Date, groupby As DateInterval) As List(Of _Trend) Implements IAccountAnalysis.GetTrend

                Dim Trends = New List(Of _Trend)

                For Each acc In Me.AccountList
                    Trends.AddRange(acc.GetTrend(t, FromDate, ToDate, groupby))
                Next

                Trends = (
                    From tr In Trends
                    Group tr By tr.Trend_Date Into g = Group
                    Select New mDB._Trend With {.Trend_Date = Trend_Date, .Value = g.Sum(Function(o) o.Value)}
                ).ToList

                Return Trends

            End Function

#End Region


        End Class

        Partial Class Message_Post

            Property PostLevel As Integer

            Private _Account As Account
            Public ReadOnly Property Account() As Account
                Get
                    If _Account Is Nothing Then
                        _Account = DB.TAB.Account.GetByPK(Me.Account_Id)
                    End If
                    Return _Account
                End Get
            End Property

            Private _ToAccount As Account
            Public ReadOnly Property ToAccount() As Account
                Get
                    If _ToAccount Is Nothing Then
                        _ToAccount = DB.TAB.Account.GetByPK(Me.To_Account_Id)
                    End If
                    Return _ToAccount
                End Get
            End Property


        End Class

        Partial Public Class Account_Filter


            Private _Filter As Account.Filter
            Public Property Filter() As Account.Filter
                Get
                    If _Filter Is Nothing Then
                        _Filter = MyApp.JSONDeserializeObj(Of Account.Filter)(Me.Filter_Json)
                    End If
                    Return _Filter
                End Get
                Set(value As Account.Filter)
                    Me._Filter = MyApp.GetSetDataJson(value, Me.Filter_Json)
                End Set
            End Property

            'Private _Filter_Data As Account.Filter
            'Public Property Filter_Data() As Account.Filter
            '    Get
            '        If _Filter_Data Is Nothing Then
            '            Dim S = DB.TAB.Data_Json.GetByPK(Me.Filter_Data_Id) '   User_Session.GetByPK(Me.Id)
            '            If S IsNot Nothing Then
            '                _Filter_Data = S.GetObj(Of Account.Filter)()  '   MyApp.JSONDeserialize(TmpSess)
            '            End If
            '        End If
            '        Return _Filter_Data
            '    End Get
            '    Set(ByVal value As Account.Filter)

            '        Me._Filter_Data = value

            '    End Set
            'End Property

            'Public Sub SaveFilter_Data()

            '    Data_Json.SaveObj(DB, Me.Filter_Data_Id, Me.Filter_Data)
            '    DB.SubmitChanges()

            'End Sub

        End Class
        Partial Public Class Account_Auth

            Public Enum ServiceType
                POST = 1
                SHARE_POST = 2
                SEARCH = 3
            End Enum

            Private _oauth As WebApi.Oauth.Oauth
            Public ReadOnly Property getOauth() As WebApi.Oauth.Oauth
                Get
                    'TODO implementare il getOauth("twitter") o getOauth("facebook") 

                    If _oauth Is Nothing Then
                        _oauth = New WebApi.Oauth.Oauth
                        _oauth.oauthConsumerKey = Me.Oauth_Consumer_Key
                        _oauth.oauthConsumerSecret = Me.Oauth_Consumer_Secret
                        _oauth.oauthToken = Me.Oauth_Token
                        _oauth.oauthTokenSecret = Me.Oauth_Token_Secret
                    End If

                    Return _oauth
                End Get
            End Property

            Private _oauth2 As WebApi.Oauth.Oauth2
            Public ReadOnly Property getOauth2() As WebApi.Oauth.Oauth2
                Get
                    'TODO implementare il getOauth("twitter") o getOauth("facebook") 

                    If _oauth2 Is Nothing Then
                        _oauth2 = New WebApi.Oauth.Oauth2(Me.Network_Id)
                        _oauth2.client_id = Me.Oauth_Consumer_Key
                        _oauth2.client_secret = Me.Oauth_Consumer_Secret
                        _oauth2.access_token = Me.Oauth_Token
                        _oauth2.refresh_token = Me.Oauth_Token_Secret
                    End If

                    Return _oauth2
                End Get
            End Property

            Public Shared Function GetFieldService(s As ServiceType) As String
                Dim FieldLastRate As String = ""

                Select Case s
                    Case ServiceType.POST
                        FieldLastRate = "last_rate_limit_post"
                    Case ServiceType.SHARE_POST
                        FieldLastRate = "last_rate_limit_share_post"
                    Case ServiceType.SEARCH
                        FieldLastRate = "last_rate_limit_search"
                End Select

                Return FieldLastRate

            End Function

            Public Sub SetLastRateLimit(s As ServiceType)
                Dim FieldLastRate = GetFieldService(s)

                Me.DB.SetFieldValue(Me, FieldLastRate, Date.UtcNow)

                Me.DB.SubmitChanges()

            End Sub

            Public Shared Function GetUserAccountAvailable(s As mDB.Account_Auth.ServiceType, network As MyApp.Network.AccType) As mDB.Account_Auth
                Dim db = mDB.GetDB '(False)
                Dim FieldLastRate = mDB.Account_Auth.GetFieldService(s)
                Dim userAcc As mDB.Account_Auth = Nothing

                userAcc = db.TAB.Account_Auth.
                    BY.Account_Auth.Enabled.
                    BY.Account_Auth.Network_id(network).
                    Where(FieldLastRate, "<", Date.UtcNow.AddMinutes(-15)).
                    OrderBy(FieldLastRate).
                    Limit(1).
                ToObj()

                Return userAcc

            End Function

            Public Shared Function SetErrorAccount(Token As String) As Boolean
                Dim db = mDB.GetDB '(False)
                'Dim Disabled As Boolean = False

                Dim ua = db.TAB.Account_Auth.
                    Where("oauth_token", "=", Token).
                ToObj

                Dim Diff = Math.Abs(DateDiff(DateInterval.Minute, Date.UtcNow, ua.Error_Account_Last_Date))

                If Diff < 8 * 60 Then
                    If ua.Error_Account_Count > 10 And Diff > 2 * 60 Then
                        ua.Disabled = 1
                        MyApp.Email.Debug.Send(SF("account disabled: {0}", ua.Account_Id))
                    Else
                        ua.Error_Account_Count += 1
                        MyApp.Email.Debug.Send(SF("account error: {0}", ua.Account_Id))
                    End If
                Else
                    ua.Error_Account_Last_Date = Date.UtcNow
                    ua.Error_Account_Count = 1
                End If

                db.SubmitChanges()

                Return ua.Disabled

            End Function


        End Class

        Partial Public Class Send_Mail


            Public Property Mail_Type() As MyApp.Email.System.Type
                Get
                    Return Me.Mail_Type_Id
                End Get
                Set(ByVal value As MyApp.Email.System.Type)
                    Me.Mail_Type_Id = value
                End Set
            End Property


            Public Function SendMail() As Boolean

                Dim data = MyApp.JSONDeserialize(Me.Data_Json)

                MyApp.Email.System.Send(Me.Mail_Type, data)

                Me.Mail_Send = True
                Me.Send_Data = Date.UtcNow

                DB.SubmitChanges()

                Return True
            End Function


        End Class

        Partial Public Class Time_Zone


            Private _TimeZone As TimeZoneInfo
            Public ReadOnly Property TimeZoneInf() As TimeZoneInfo
                Get
                    If _TimeZone Is Nothing Then
                        _TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Me.Time_Zone_Code)
                    End If
                    Return _TimeZone
                End Get
            End Property



        End Class

#End Region


    End Class

End Namespace
